Async functions
async/await gives Promise-based code a linear structure. It keeps asynchronous logic readable and makes try/catch handling feel close to synchronous code.
Overview
async/await gives Promise-based code a linear structure. It keeps asynchronous logic readable and makes try/catch handling feel close to synchronous code.
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 55 | 15 | 52 | 10.1 | 55 | 10.3 | |
| The AsyncFunction() constructor creates AsyncFunction objects. | 55 | 15 | 52 | 10.1 | 55 | 10.3 |
| Other | ||||||
| The async function keywords can be used to define an async function inside an expression. | 55 | 15 | 52 | 10.1 | 55 | 10.3 |
| The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or at the top level of a module. | 55 | 14 | 52 | 10.1 | 55 | 10.3 |
| The async function declaration creates a binding of a new async function to a given name. The await keyword is permitted within the function body, enabling asynchronous, promise-based behavior to be written in a cleaner style and avoiding the need to explicitly configure promise chains. | 55 | 15 | 52 | 10.1 | 55 | 10.3 |
Syntax
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) throw new Error('Failed to retrieve');
const user = await response.json();
return user;
} catch (error) {
console.error('Error:', error.message);
}
}
// Top-level await (ES modules)
const data = await fetchUserData(1); Live demo
Sequential async flow
Await three steps in order and compare the output with the order written in the source.
try/catch around awaited work
Handle successful and failing Promises with one control-flow structure.
Use cases
Request orchestration
Wait for one result before making the next request when later work depends on earlier data.
Readable error handling
Wrap asynchronous code in try/catch blocks instead of scattering catch handlers through a long chain.
Cautions
- await pauses only inside async functions or modules with top-level await support.
- Independent tasks should usually start in parallel before awaiting, rather than one after another by accident.
Accessibility
- Loading indicators should describe what is happening and when the UI becomes ready again after awaited work completes.
Related links
Powered by web-features