The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax

async function name([param[, param[, ... param]]]) {
statements
}

Parameters

name

The function name.

param

The name of an argument to be passed to the function.

statements

The statements comprising the body of the function.

Return value

An AsyncFunction object, representing an asynchronous function which executes the code contained within the function.

Description

When an async function is called, it returns a Promise. When the async function returns a value, the Promise will be resolved with the returned value. When the async function throws an exception or some value, the Promise will be rejected with the thrown value.

An async function can contain an await expression, that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

The purpose of async/await functions is to simplify the behavior of using promises synchronously and to perform some behavior on a group of Promises. Just as Promises are similar to structured callbacks, async/await is similar to combining generators and promises.

Do not confuse await for Promise.all

In add1, execution suspends 2 seconds for the first await, and then again another 2 seconds for the second await. The second timer is not created until the first has already fired. In add2, both timers are created, and then both are awaited. This leads it to resolve in 2 rather than 4 seconds, because the timers are running concurrently. But both of the await calls are still run in series, not in parallel: this is not some automatic application of Promise.all. If you wish to await two or more promises in parallel, you must still use Promise.all.

Rewriting a promise chain with an async function

An API that returns a Promise will result in a promise chain, and it splits the function into many parts. Consider the following code: