Summary: Async Functions and Await Expressions

Get a brief summary of async functions and await expressions.

Asynchronous functions

Async functions allow us to use promises without manually assigning fulfillment and rejection handlers. We can turn any function into an async function by adding the async keyword before the function definition.

The return value of an async function is always a promise. If we return a promise from the async function, then it is duplicated and returned to the call site; if we return a non-promise value, then the value is resolved to a promise and returned to the call site.

Error handling

Errors thrown inside an async function are caught and returned as rejected promises. Due to this behavior, we can’t catch errors originating in an async function using try-catch. Instead, we need to assign a rejection handler to the returned promise.

Iterating with the for-await-of loop

Async functions enable two special types of syntax: the await expression and the for-await-of loop. The await expression is used to automatically assign fulfillment and rejection handlers to a promise so that the fulfillment value becomes the return value of the await expression and a rejection causes an error to be thrown. Similarly, the for-await-of loop operates on an async iterable and allows the use of promises instead of a loop. The for-await-of loop waits for each promise returned from the async iterable to fulfill before going on to the next promise. If a promise from the async iterable is rejected, then an error is thrown.

We can use top-level await expressions outside of async functions at the top level of JavaScript modules. This capability is not available in scripts.

Get hands-on with 1400+ tech skills courses.