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
.
variable = await expression;
Where:
expression
is a promise or any value to wait forvariable
returns the fulfilled value of the promise or itselfIf 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
.
Let’s take a look at a few examples:
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();
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 calledvar x = await 20;console.log(x);}case3();
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