How to use async and await in JavaScript

What is an async keyword?

An async keyword turns a regular function into an asynchronous function.

Note: An asynchronous function is a function that runs in its own timing—without waiting for others to finish their execution first.

By default, an async function returns a resolved or rejected promise object.

Example

Let’s look at the code below:

// Define an async function:
async function myMomsPromise() {
return 'I get a book';
}
// Invoke the myMomsPromise() asynchronous function:
console.log(myMomsPromise());
// The invocation above will return:
// Promise { <state>: "fulfilled", <value>: "I get a book" }

We use the async keyword to convert myMomsPromise() to an asynchronous function. Therefore, the function's invocation returns a promise object rather than a string value.

What is an awaitkeyword?

An await keyword instructs a function to wait for a promise to be settled before continuing its execution.

Note the following:

  • The await keyword works only inside an async function in regular JavaScript code. However, in a JavaScript module, we can use await on its own, that is, outside an async function.

  • We can use zero or more await expressions in an async function.

Example

Let's look at the code below:

// Define an async function:
async function showMomsPromise() {
const myMomsPromise = new Promise(function (resolve, reject) {
setTimeout(resolve, 5000, "I get a book");
});
console.log(await myMomsPromise);
}
// Invoke the showMomsPromise() asynchronous function:
showMomsPromise();
// The invocation above will first return:
// Promise { <state>: "pending" }
// Then, after 5000 milliseconds (5 seconds), the invocation will return:
// "I get a book"

We use the await keyword to instruct showMomsPromise() to wait for myMomsPromise() to be settled before continuing its execution.

Suppose we omit the await keyword in the snippet above. In such a case, the console.log() statement would invoke myMomsPromise() immediately—without waiting for its promise to resolve.

Consequently, showMomsPromise()'s invocation would return a fulfilled promise resolved with an undefined value.

Let's look at the code below:

// Define an async function:
async function showMomsPromise() {
const myMomsPromise = new Promise(function (resolve, reject) {
setTimeout(resolve, 5000, 'I get a book');
});
console.log(myMomsPromise);
}
// Invoke the showMomsPromise() asynchronous function:
showMomsPromise();
// The invocation above will first return:
// Promise { <state>: "pending" }
// Immediately afterward, the invocation will return:
// Promise { <state>: "fulfilled", <value>: undefined }

JavaScript immediately invokes the above console.log(myMomsPromise) statement because it has no await keyword.

Free Resources