Async & Await

ES5

function myFunc(){
  return 'Hello';
}
console.log(myFunc());

Async

async function myFunc(){
  return 'Hello';
}
myFunc()
  .then(res => console.log(res))
async function myFunc(){

  const promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve('Hello'), 1000);
  });

  const error = false;

  if(!error){
    // Wait until promise is resolved
    const res = await promise; 
    return res;
  } else{
    await Promise.reject(new Error('Something went wrong'));
  }
}

myFunc()
  .then(res => console.log(res));

async function getUsers(){

  // Await response of the fetch call
  const response = await fetch('https://jsonplaceholder.typicode.com/users');

  // Only proceed when its resolved
  const data = await response.json();

  // Only proceed when the second promise is resolved
  return data;
}
getUsers().then(users => console.log(users));
Was this page helpful?

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *