async / await (Node.js)

async/await is syntax that makes Promise-based code read like ordinary synchronous code. An async function returns a Promise, and await pauses it until a Promise settles, returning the value or throwing the rejection.

Node.js

async/await is sugar over Promises that removes the .then chains. Mark a function async and you can await any Promise inside it; execution pauses (without blocking the event loop) until the Promise resolves, then continues with the resolved value. Errors from rejected Promises surface as exceptions you catch with try/catch.

The big win is readability: sequential async steps look like normal top-to-bottom code, and error handling uses familiar try/catch rather than .catch callbacks. Under the hood it is still Promises — an async function always returns one — so it interoperates with .then and Promise.all.

Gotchas: awaiting in a loop runs steps one at a time (sequentially); to run independent async tasks in parallel, start them and await Promise.all of the results. And remember await only works inside an async function (or at the top level of an ES Module).

Syntax

async function f() { const x = await promise; }

Examples

JavaScript

const fs = require("fs/promises");

async function main() {
  try {
    const text = await fs.readFile("data.txt", "utf8");
    console.log("length:", text.length);
  } catch (err) {
    console.error("failed:", err.message);
  }
}
main();

Learn it in a lesson

See also

Back to the Dictionary