Browse topics

async and await

Version
es2025
Since
es2017
Review
Draft

Summary#

An async function always returns a promise. Inside it, await pauses that function until a promise settles, then produces the fulfillment value or throws the rejection reason.

Syntax#

js
async function name(parameter) {
  const value = await promise;
  return value;
}

Example#

js
/** @param {string} id */
async function loadUser(id) {
  if (!id) throw new Error("missing id");
  return { id, name: "Ada" };
}

const pending = loadUser("u1");
console.log(pending instanceof Promise);
console.log((await pending).name);

try {
  await loadUser("");
} catch (error) {
  console.log(error instanceof Error && error.message);
}

Expected output#

Text
true
Ada
missing id

Common mistakes#

array.forEach(async (item) => ...) does not wait for the callbacks. Use for...of with await to run in sequence, or await Promise.all(array.map(...)) to run concurrently. Inside try, write return await task() when the local catch must handle a rejection.

Version applicability#

ES2017 added async functions. The example also uses ES2022 top-level await. Save it as an .mjs file to run it as a module in Node.js.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0