Async-Await

asynchronous functions and controlling the execution of functions using the await operator

The ability to write asynchronous functions is a major update in ES2017.

What are the asynchronous functions?

Asynchronous functions are functions that return a promise. We denote them by using the async keyword.

Press + to interact
const loadData = async function( value ) {
if ( value > 0 ) {
return { data: value };
} else {
throw new Error( 'Value must be greater than 0' );
}
}
loadData( 1 ).then( response => console.log( response ) );
loadData( 0 ).catch( error => console.log( error ) );

When loadData returns an object, the return value is wrapped into a promise. As this promise is resolved, the then callback is executed, console logging the response.

When loadData is called with the argument 0, an error is thrown. This error is wrapped into a rejected promise, which is handled by the catch callback.

In general, return values of an async function are wrapped into a resolved promise, except if the return value is a promise itself. In the latter case, the promise is returned. Errors thrown in an async function are caught and wrapped into a rejected promise.

The await operator

Await is a prefix operator standing in front of a promise.

As long as the promise behind the await operator is pending, await blocks execution. As soon as the promise is resolved, await returns the fulfillment value of the promise. As soon as the promise is rejected, await throws ...