async await examples

Example 1: async await

const data = async ()  => {
  const got = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  
  console.log(await got.json())
}

data();

Example 2: how to make an async function

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

//async function:
async function asyncCall() {
  console.log('calling');
  const result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

asyncCall();

Example 3: async await javascript

function hello() {
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve('I am adam.');
    }, 2000);
  });
}
async function async_msg() {
  try {
    let msg = await hello();
    console.log(msg);
  }
  catch(e) {
    console.log('Error!', e);
  }
}
async_msg(); //output - I am adam.

Example 4: async and await

function delayResult() {
 return new Promise(resolve => {
   setTimeout(() => {
     resolve(‘Done’);
   }, 5000)
 })
}
async function getResult() {
 let result = await delayResult();
 return result;
}
getResult();

Example 5: await async

function afterPrintSave() {
    Xrm.Page.data.save().then(
        function () {
            resolve();
        },
        function (err) {
            resolve(alert(err.message));
        }
    );
}

Tags:

Misc Example