Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 133 ยท Asynchronous Programming

async/await Patterns

Master async/await in Node.js - sequential versus parallel awaits, try/catch, loops and forEach traps, top-level await, async stack traces and the mistakes that cause silent bugs.

async and await let you write asynchronous code that reads like ordinary synchronous code. An async function always returns a promise, and await pauses that function (not the whole program) until a promise settles. While it is paused, the event loop keeps serving everything else. Once you internalize that single sentence, most of the confusing behavior of async code becomes predictable.

This lesson is about patterns: when to run things one after another and when side by side, how errors behave, why forEach and await do not mix, the mistakes that produce silent bugs, and how async stack traces help you debug. Everything here uses ES modules, where await also works at the top level of the file.

The basics in one example

An async function returns a promise no matter what: if it returns a value, the promise fulfills with it; if it throws, the promise rejects. await unwraps a promise's value, or throws its rejection reason right at that line.

Node.js async functions return promises

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two small details. The body of an async function runs synchronously until its first await, so side effects before the first await happen immediately when you call it. And awaiting a non-promise is allowed but pointless; it just yields to the microtask queue once.

Sequential versus parallel

The most common performance mistake with await is accidentally running independent work one step at a time. If operation B does not need the result of operation A, start both first and await afterwards.

Node.js Sequential awaits versus Promise.all

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In the log, sequential shows start A, end A, start B, end B. The parallel version shows both starts first, and end B before end A, because B is faster. Total time drops from "A + B" to "the slower of the two". Another way to write the parallel version is to start the promises first and await them later:

NODE
const userPromise = loadUser(id);      // starts now
const ordersPromise = loadOrders(id);  // starts now, too
const user = await userPromise;
const orders = await ordersPromise;

Be careful with this form. If ordersPromise rejects while you are still awaiting userPromise, nobody has attached a handler to it yet, and Node may report an unhandled rejection. Promise.all attaches handlers to everything immediately, which is why it is the safer default.

Rule of thumb: await in sequence only when a step needs the result of the previous one. Otherwise group the independent steps with Promise.all (or Promise.allSettled when partial failure is fine).

Error handling with try/catch/finally

Because await throws the rejection reason, ordinary try/catch/finally works across asynchronous steps. This is the biggest readability win over callbacks.

Node.js try, catch and finally with await

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Note return await query(...) inside the try. Without await, the function would return the pending promise immediately, the try block would be left, finally would run before the query finished, and a rejection would skip the catch entirely. Inside a try block, always await what you return. Outside of try, return promise and return await promise behave the same (the latter adds a tiny cost and a clearer stack trace).

Catching several kinds of errors

When different failures need different responses, inspect err.name, err.code or use instanceof. Rethrow what you do not understand:

NODE
try {
  await doWork();
} catch (err) {
  if (err.code === 'ENOENT') {
    console.log('file missing, using defaults');
  } else {
    throw err; // not ours: let someone else decide
  }
}

Loops and await

Inside a for...of or for loop, await pauses the loop, giving you reliable sequential processing. The trap is forEach, map, filter and friends: they call your function for each item, and an async callback returns a promise that the method ignores.

Node.js forEach does not wait

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first line shows the empty array, the proof that forEach did not wait. The fixes:

  • for...of + await when order matters, when each step depends on the previous one, or when you must not overload a service.
  • map + Promise.all when everything may run at once. For thousands of items that can be too much at once; see Concurrency Control and Queues for limits.
  • reduce is possible but hard to read; prefer a loop.

for await...of loops over an async iterable (a stream, or an async generator) and awaits each value, as covered in Async Iterators and Generators.

Node.js for await over an async source

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Top-level await

In an ES module (our editor runs your code as one; so does any .mjs file or a project with "type": "module"), you may use await outside any function. The module simply waits before finishing evaluation. That is perfect for scripts and for loading configuration, and it makes your examples shorter. Remember two costs: a module that awaits something slow delays everything that imports it, and in CommonJS files top-level await is a syntax error (wrap the code in an async function there).

Common mistakes

Forgetting to await

A missing await gives you a promise where you expected a value. It never throws at that point, which makes it the sneakiest async bug.

Node.js A forgotten await

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first check passes for everybody, and the template string prints [object Promise]. A linter rule such as @typescript-eslint/no-floating-promises (or ESLint's require-await and no-misused-promises) catches these before they reach production. Notice also that isAllowed(user) here is a "floating" promise whose result nobody reads; if it rejected, you would get an unhandled rejection.

Awaiting in a hot path

Each await costs a trip through the microtask queue. In normal code that is invisible, but inside a tight loop doing millions of small steps it adds up. Do not await values you know are plain, and do not wrap synchronous code in async functions "just in case".

Mixing styles

Do not mix .then() chains and await in the same function without a reason. Pick await; use .then/.catch for small one-liners such as fetchData().catch(() => null) to give a fallback value.

Async stack traces

When an error passes through several awaits, V8 reconstructs an async stack trace: the lines marked at async are functions that were waiting for the one above them. That is why modern traces still show who called what, even after timers and I/O in between.

Node.js An async stack trace (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The output starts with Error: row 1 is corrupt followed by lines such as at readRow (main.mjs:5:9), at async loadReport (main.mjs:9:17) and at async main (main.mjs:14:3), ending in a file:// loader frame. Read them from the top: the first line is where the error was created, and each at async line is a caller that was suspended on an await. The trace only includes callers that were awaiting: if you call a function without await (fire and forget), it disappears from the trace.

Pass --enable-source-maps (our runner already does) so that TypeScript or bundled code still points at your original lines.

Never write async on a function that does not need it. An async function that contains no await still works, but it hides synchronous throws inside a rejected promise and costs an extra microtask. Also do not pass an async function to APIs that ignore return values (event listeners, setInterval, array.forEach) without handling its rejection, or the error becomes an unhandled rejection.

Putting it together: a tiny parallel pipeline

Node.js Sequential dependencies plus parallel fan-out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

This is the shape of most real async code: one or two steps that depend on each other, with a parallel fan-out in the middle. If you remember only one thing, remember to ask of every await: does the next line need this result?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does an async function always return?

    Calling an async function always gives a promise. It fulfills with the returned value or rejects with the thrown error.
  2. 2. Two requests do not depend on each other. Which code runs them in parallel?

    Promise.all starts both operations immediately and waits for both. The other forms run them one after the other.
  3. 3. Why does items.forEach(async (item) => { await save(item); }) not wait for the saves?

    forEach calls the callback and discards its return value, so it never waits for the promises. Use for...of or Promise.all with map.
  4. 4. Why write return await query() inside a try block?

    Without await the pending promise is returned straight away, the try block ends, and a later rejection bypasses the catch.
  5. 5. What does if (isAllowed(user)) do when isAllowed is async and you forgot to await it?

    The condition receives a Promise object, which is always truthy. The result of the check is never read.

Summary

  • async functions return promises; await pauses only the current function and unwraps a promise or throws its rejection.
  • Await in sequence only for dependent steps; use Promise.all for independent work.
  • try/catch/finally works across awaits; use return await inside try.
  • for...of is sequential; forEach with async callbacks does not wait; map plus Promise.all is parallel.
  • Top-level await works in ES modules only.
  • A forgotten await yields a truthy promise instead of a value; lint for floating promises.
  • at async frames in stack traces show the chain of awaiting callers.

Next: Concurrency Control and Queues