JavaScript

Last Updated: 4/13/2023

async/await

async

  • async function always returns a promise. other values are wrapped in a resolved promise automatically.
async function f() {
  return 1;
}

f().then(alert); // 1

equivalent to

async function f() {
  return Promise.resolve(1);
}

f().then(alert); // 1

await

  • await, works only inside async functions
  • await makes JavaScript wait until that promise settles and returns its result.
  • await suspends the function execution until the promise settles, and then resumes it with the promise result. That doesn’t cost any CPU resources, because the JavaScript engine can do other jobs in the meantime: execute other scripts, handle events, etc.
async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // wait until the promise resolves (*)

  alert(result); // "done!"
}

f();

With try catch

async function display() {
     const promise = new Promise(function(resolve, reject){
         setTimeout(() => {
             reject("fail");
         }, 3000);
     })
     try {
         await promise;    
     } catch (error) {
         console.log("error")    
     }
 }

With Catch

async function display() {
     const promise = new Promise(function(resolve, reject){
         setTimeout(() => {
             reject("fail");
         }, 3000);
     })
     await promise;
 }
 display().catch(function(error){
     console.log("error")
 });