What is the await operator in JavaScript?

The await operator is used inside an async function to wait for a promise.

The await expression causes async function execution to pause until a Promise is returned. When returned, the value of the await expression is that of the fulfilled Promise.

Syntax

variable = await expression;

Where:

  • expression is a promise or any value to wait for
  • variable returns the fulfilled value of the promise or itself

If the promise is rejected, the await expression throws the rejected value into a catch block. If the expression’s value is not a Promise, it’s converted to a resolved Promise.

An await splits execution flow. After the await defers the continuation of the async function, execution of subsequent statements ensues. If await is the last statement, the function returns a pending promise.

Example

Let’s take a look at a few examples:

1. Awaiting a promise within an await

It waits for the promise to be fulfilled and returns the value. In this case, the function waits for the token to get the value and then prints it.

function getToken() {
return new Promise(x => {
window.localStorage.getItem("token")
});
}
async function case1() {
var x = await getToken();
console.log(x)
}
case1();

2. Conversion to promise

In case the return value is not a Promise, it automatically converts the value to a resolved Promise.

async function case3() {
//await for 20 seconds when called
var x = await 20;
console.log(x);
}
case3();

3. Promise rejection

In case the Promise is rejected, the rejected value is returned.

The following code shows how this value can be displayed:

async function case4() {
try {
var z = await Promise.reject(20);
}
catch(e) {
console.error(e);
}
}
case4();

Note: If a function rejects a Promise, you can use the catch clause rather than using try/except to view the error.

They way this code is used is shown below:

var response = await promisedFunction()
.then(console.log("No error!"))
.catch((err) =>
console.error(err)
);
// response will be undefined if the promise is rejected

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved