Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

async function

BaselineWidely available

Theasync function declaration creates abinding of a new async function to a given name. Theawait 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.

You can also define async functions using theasync function expression.

Try it

function resolveAfter2Seconds() {  return new Promise((resolve) => {    setTimeout(() => {      resolve("resolved");    }, 2000);  });}async function asyncCall() {  console.log("calling");  const result = await resolveAfter2Seconds();  console.log(result);  // Expected output: "resolved"}asyncCall();

Syntax

js
async function name(param0) {  statements}async function name(param0, param1) {  statements}async function name(param0, param1, /* …, */ paramN) {  statements}

Note:There cannot be a line terminator betweenasync andfunction, otherwise a semicolon isautomatically inserted, causingasync to become an identifier and the rest to become afunction declaration.

Parameters

name

The function's name.

paramOptional

The name of a formal parameter for the function. For the parameters' syntax, see theFunctions reference.

statementsOptional

The statements comprising the body of the function. Theawaitmechanism may be used.

Description

Anasync function declaration creates anAsyncFunction object. Each time when an async function is called, it returns a newPromise which will be resolved with the value returned by the async function, or rejected with an exception uncaught within the async function.

Async functions can contain zero or moreawait expressions. Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected. The resolved value of the promise is treated as the return value of the await expression. Use ofasync andawait enables the use of ordinarytry /catch blocks around asynchronous code.

Note:Theawait keyword is only valid inside async functions within regular JavaScript code. If you use it outside of an async function's body, you will get aSyntaxError.

await can be used on its own withJavaScript modules.

Note:The purpose ofasync/await is to simplify the syntaxnecessary to consume promise-based APIs. The behaviorofasync/await is similar to combininggenerators andpromises.

Async functions always return a promise. If the return value of an async function isnot explicitly a promise, it will be implicitly wrapped in a promise.

For example, consider the following code:

js
async function foo() {  return 1;}

It is similar to:

js
function foo() {  return Promise.resolve(1);}

Note that even though the return value of an async function behaves as if it's wrapped in aPromise.resolve, they are not equivalent. An async function will return a differentreference, whereasPromise.resolve returns the same reference if the given value is a promise. It can be a problem when you want to check the equality of a promise and a return value of an async function.

js
const p = new Promise((res, rej) => {  res(1);});async function asyncReturn() {  return p;}function basicReturn() {  return Promise.resolve(p);}console.log(p === basicReturn()); // trueconsole.log(p === asyncReturn()); // false

The body of an async function can be thought of as being split by zero or more awaitexpressions. Top-level code, up to and including the first await expression (if there isone), is run synchronously. In this way, an async function without an await expressionwill run synchronously. If there is an await expression inside the function body,however, the async function will always complete asynchronously.

For example:

js
async function foo() {  await 1;}

It is also equivalent to:

js
function foo() {  return Promise.resolve(1).then(() => undefined);}

Code after each await expression can be thought of as existing in a.thencallback. In this way a promise chain is progressively constructed with each reentrantstep through the function. The return value forms the final link in the chain.

In the following example, we successively await two promises. Progress moves throughfunctionfoo in three stages.

  1. The first line of the body of functionfoo is executed synchronously,with the await expression configured with the pending promise. Progress throughfoo is then suspended and control is yielded back to the function thatcalledfoo.
  2. Some time later, when the first promise has either been fulfilled or rejected,control moves back intofoo. The result of the first promise fulfillment(if it was not rejected) is returned from the await expression. Here1 isassigned toresult1. Progress continues, and the second await expressionis evaluated. Again, progress throughfoo is suspended and control isyielded.
  3. Some time later, when the second promise has either been fulfilled or rejected,control re-entersfoo. The result of the second promise resolution isreturned from the second await expression. Here2 is assigned toresult2. Control moves to the return expression (if any). The defaultreturn value ofundefined is returned as the resolution value of thecurrent promise.
js
async function foo() {  const result1 = await new Promise((resolve) =>    setTimeout(() => resolve("1")),  );  const result2 = await new Promise((resolve) =>    setTimeout(() => resolve("2")),  );}foo();

Note how the promise chain is not built-up in one go. Instead, the promise chain isconstructed in stages as control is successively yielded from and returned to the asyncfunction. As a result, we must be mindful of error handling behavior when dealing withconcurrent asynchronous operations.

For example, in the following code an unhandled promise rejection error will be thrown,even if a.catch handler has been configured further along the promisechain. This is becausep2 will not be "wired into" the promise chain untilcontrol returns fromp1.

js
async function foo() {  const p1 = new Promise((resolve) => setTimeout(() => resolve("1"), 1000));  const p2 = new Promise((_, reject) =>    setTimeout(() => reject(new Error("failed")), 500),  );  const results = [await p1, await p2]; // Do not do this! Use Promise.all or Promise.allSettled instead.}foo().catch(() => {}); // Attempt to swallow all errors...

async function declarations behave similar tofunction declarations — they arehoisted to the top of their scope and can be called anywhere in their scope, and they can be redeclared only in certain contexts.

Examples

Async functions and execution order

js
function resolveAfter2Seconds() {  console.log("starting slow promise");  return new Promise((resolve) => {    setTimeout(() => {      resolve("slow");      console.log("slow promise is done");    }, 2000);  });}function resolveAfter1Second() {  console.log("starting fast promise");  return new Promise((resolve) => {    setTimeout(() => {      resolve("fast");      console.log("fast promise is done");    }, 1000);  });}async function sequentialStart() {  console.log("== sequentialStart starts ==");  // 1. Start a timer, log after it's done  const slow = resolveAfter2Seconds();  console.log(await slow);  // 2. Start the next timer after waiting for the previous one  const fast = resolveAfter1Second();  console.log(await fast);  console.log("== sequentialStart done ==");}async function sequentialWait() {  console.log("== sequentialWait starts ==");  // 1. Start two timers without waiting for each other  const slow = resolveAfter2Seconds();  const fast = resolveAfter1Second();  // 2. Wait for the slow timer to complete, and then log the result  console.log(await slow);  // 3. Wait for the fast timer to complete, and then log the result  console.log(await fast);  console.log("== sequentialWait done ==");}async function concurrent1() {  console.log("== concurrent1 starts ==");  // 1. Start two timers concurrently and wait for both to complete  const results = await Promise.all([    resolveAfter2Seconds(),    resolveAfter1Second(),  ]);  // 2. Log the results together  console.log(results[0]);  console.log(results[1]);  console.log("== concurrent1 done ==");}async function concurrent2() {  console.log("== concurrent2 starts ==");  // 1. Start two timers concurrently, log immediately after each one is done  await Promise.all([    (async () => console.log(await resolveAfter2Seconds()))(),    (async () => console.log(await resolveAfter1Second()))(),  ]);  console.log("== concurrent2 done ==");}sequentialStart(); // after 2 seconds, logs "slow", then after 1 more second, "fast"// wait above to finishsetTimeout(sequentialWait, 4000); // after 2 seconds, logs "slow" and then "fast"// wait againsetTimeout(concurrent1, 7000); // same as sequentialWait// wait againsetTimeout(concurrent2, 10000); // after 1 second, logs "fast", then after 1 more second, "slow"

await and concurrency

InsequentialStart, execution suspends 2 seconds for the firstawait, and then another second for the secondawait. Thesecond timer is not created until the first has already fired, so the code finishesafter 3 seconds.

InsequentialWait, both timers are created and thenawaited.The timers run concurrently, which means the code finishes in 2 rather than 3 seconds,i.e., the slowest timer.However, theawait calls still run in series, which means the secondawait will wait for the first one to finish. In this case, the result ofthe fastest timer is processed after the slowest.

If you wish to safely perform other jobs after two or more jobs run concurrently and are complete, you must await a calltoPromise.all() orPromise.allSettled() before that job.

Warning:The functionssequentialWait andconcurrent1are not functionally equivalent.

InsequentialWait, if promisefast rejects before promiseslow is fulfilled, then an unhandled promise rejection error will beraised, regardless of whether the caller has configured a catch clause.

Inconcurrent1,Promise.all wires up the promisechain in one go, meaning that the operation will fail-fast regardless of the order ofrejection of the promises, and the error will always occur within the configuredpromise chain, enabling it to be caught in the normal way.

Rewriting a Promise chain with an async function

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

js
function getProcessedData(url) {  return downloadData(url) // returns a promise    .catch((e) => downloadFallbackData(url)) // returns a promise    .then((v) => processDataInWorker(v)); // returns a promise}

it can be rewritten with a single async function as follows:

js
async function getProcessedData(url) {  let v;  try {    v = await downloadData(url);  } catch (e) {    v = await downloadFallbackData(url);  }  return processDataInWorker(v);}

Alternatively, you can chain the promise withcatch():

js
async function getProcessedData(url) {  const v = await downloadData(url).catch((e) => downloadFallbackData(url));  return processDataInWorker(v);}

In the two rewritten versions, notice there is noawait statement after thereturn keyword, although that would be valid too: The return value of anasync function is implicitly wrapped inPromise.resolve - ifit's not already a promise itself (as in the examples).

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-async-function-definitions

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp