ES6 ~ Async and Await - rohit120582sharma/Documentation GitHub Wiki

Async/Await is special syntax to work with promises in a more comfort fashion which is surprisingly easy to understand and use.

Async keyword is used to define an asynchronous function.

Await keyword is used to pause async function execution until a Promise is fulfilled, that is resolved or rejected, and to resume execution of the async function after fulfillments. When resumed, the value of the await expression is that of the fulfilled Promise.


Key points:

  • Functions with the async keyword will always return a promise that will either resolve to the value X or throw an error.
  • Await can only be used inside and async function.
  • Multiple awaits will always run in sequential order under a same function.
  • If a promise resolves normally, then await promise returns the result. But in case of a rejection it throws the error, just if there were a throw statement at that line.
async function asyncFunction() {
    const promise = new Promise((resolve, reject) => {
        setTimeout(() => resolve("i am resolved!"), 1000)
    });

    const result = await promise; 
    // wait till the promise resolves (*)

    console.log(result); // "i am resolved!"
}

asyncFunction();

Async functions are a syntax sugar to improve the language-level model for writing asynchronous code. Async functions are built on top of ECMAScript 6 features like generators.


⚠️ **GitHub.com Fallback** ⚠️