JavaScript Reference ยท Statements and Declarations
The async function declaration
Reference for the JavaScript async function declaration: how it always returns a promise, how await pauses it, error handling, and sequential versus parallel work.
An async function is a function that always returns a promise and may use the await operator in its body. Whatever the function returns becomes the fulfillment value of that promise; if the body throws, the promise is rejected with the error.
Inside the function, await somePromise pauses that function (not the whole program) until the promise settles, so asynchronous steps can be written in a top-to-bottom style.
async function loadUser(id) { const response = await fetch(`/api/users/${id}`); return response.json(); }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
async function name(params) { statements } const f = async function (params) { statements }; const g = async (params) => expression; const obj = { async method() {} }; class C { async method() {} }
Return value: a Promise that fulfills with the returned value, or rejects with a thrown error.
Usage notes
- Always a promise. Even
async function f() { return 1 }returns a promise; callers mustawaitit or use.then(). - Code before the first
awaitruns synchronously when you call the function. The rest continues in later microtasks. awaitoutside async functions is allowed only at the top level of ES modules (and in some consoles).- Sequential by default. Two
awaits in a row run one after another. To run work concurrently, start the promises first and wait withPromise.all(). - Forgetting
awaitgives you a pending promise instead of the value, and errors inside it surface as unhandled rejections. - Handle rejections. Wrap awaits in
try...catchor attach.catch()to the returned promise. awaitin loops.awaitin afor...ofloop processes items one at a time;forEachwith an async callback does not wait for them.- Hoisting. An async function declaration is hoisted like a normal function declaration; an async function expression is not.
- Not a constructor. Async functions cannot be called with
new.
Browser support
Async functions are supported by all current browsers and Node.js. Top-level await needs a module script.
Related
await,Promise,Promise.all()function, async and await- Lesson: Async and await, Promises