JavaScript await

Profile picture for user arilio666

To wait for a promise, javascript await is used. It can only exist inside an async function within regular javascript code. Await makes the code wait for a bit until the promise returns a result and can only make the async block wait.

const getVal = async() => {
    var x = await "Hii"; 
    console.log(x);
}
 
console.log(1);
getVal();
console.log(2);
1
2
Hii
  • Due to the usage of await keyword, the console has printed number 2 before "Hii."
  • The await keyword causes the async function execution to pause until a promise has settled and resumes execution of the async function after fulfillment.
  • When it resumes, the value of the await is the same as that of the value of the fulfilled promise.
  • When the promise is rejected, await throws reject value.

Let us see a real-time example of it.

function resumeAfterSomeTime(x) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve(x);
      }, 2000);
    });
  }
  
  async function asyncFunc() {
    const x = await resumeAfterSomeTime(200);
    console.log(x); 
  }
  
  asyncFunc();
200
  • We can see here it waited for the promise to be fulfilled and returned the value.

Conclusion:

  • So this is how an await works, and it is simple.
  • It just waits and delivers the message.