The async function
declaration defines an asynchronous function, which returns an AsyncFunction
object. An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise
to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.
You can also define async functions using an async function expression.
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
A Promise
which will be resolved with the value returned by the async function, or rejected with an uncaught exception thrown from within the async function.
Description
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.
Remember, the await
keyword is only valid inside async
functions. If you use it outside of an async
function's body, you will get a SyntaxError
.
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.
Examples
Simple example
var resolveAfter2Seconds = function() { console.log("starting slow promise"); return new Promise(resolve => { setTimeout(function() { resolve(20); console.log("slow promise is done"); }, 2000); }); }; var resolveAfter1Second = function() { console.log("starting fast promise"); return new Promise(resolve => { setTimeout(function() { resolve(10); console.log("fast promise is done"); }, 1000); }); }; var sequentialStart = async function() { console.log('==SEQUENTIAL START=='); // If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise. const slow = await resolveAfter2Seconds(); const fast = await resolveAfter1Second(); console.log(slow); console.log(fast); } var concurrentStart = async function() { console.log('==CONCURRENT START with await=='); const slow = resolveAfter2Seconds(); // starts timer immediately const fast = resolveAfter1Second(); console.log(await slow); console.log(await fast); // waits for slow to finish, even though fast is already done! } var stillConcurrent = function() { console.log('==CONCURRENT START with Promise.all=='); Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then((messages) => { console.log(messages[0]); // slow console.log(messages[1]); // fast }); } var parallel = function() { console.log('==PARALLEL with Promise.then=='); resolveAfter2Seconds().then((message)=>console.log(message)); resolveAfter1Second().then((message)=>console.log(message)); } sequentialStart(); // after 2 seconds, logs "slow", then after 1 more second, "fast" // wait above to finish setTimeout(concurrentStart, 4000); // after 2 seconds, logs "slow" and then "fast" // wait again setTimeout(stillConcurrent, 7000); // same as concurrentStart // wait again setTimeout(parallel, 10000); // trully parallel: after 1 second, logs "fast", then after 1 more second, "slow"
Do not confuse await
for Promise#then
In sequentialStart
, execution suspends 2 seconds for the first await
, and then again another 1 second for the second await
. The second timer is not created until the first has already fired.
In concurrentStart
, both timers are created and then await
ed. The timers are running concurrently but the await
calls are still running in series, meaning the second await
will wait for the first one to finish. This leads the code to finish in 2 rather than 3 seconds, which is the time the slowest timer needs. The same happens in stillConcurrent
using Promise.all
this time.
If you wish to await two or more promises in parallel, you must still use Promise#then
, as parallel
does in the example.
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:
function getProcessedData(url) { return downloadData(url) // returns a promise .catch(e => { return downloadFallbackData(url) // returns a promise }) .then(v => { return processDataInWorker(v); // returns a promise }); }
it can be rewritten with a single async
function as follows:
async function getProcessedData(url) { let v; try { v = await downloadData(url); } catch(e) { v = await downloadFallbackData(url); } return processDataInWorker(v); }
Note that in the above example, there is no await
statement on the return
statement, because the return value of an async function
is implicitly wrapped in Promise.resolve
.
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript Latest Draft (ECMA-262) The definition of 'async function' in that specification. |
Draft | Initial definition in ES2017. |
ECMAScript 2017 (ECMA-262) The definition of 'async function' in that specification. |
Standard |
Browser compatibility
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Basic support | Chrome Full support 55 | Edge Full support Yes | Firefox Full support 52 | IE No support No | Opera Full support 42 | Safari Full support 10.1 | WebView Android Full support Yes | Chrome Android Full support 55 | Edge Mobile Full support Yes | Firefox Android Full support 52 | Opera Android Full support 42 | Safari iOS Full support 10.1 | Samsung Internet Android Full support 6.0 | nodejs
Full support
7.6.0
|
Legend
- Full support
- Full support
- No support
- No support
- User must explicitly enable this feature.
- User must explicitly enable this feature.