Skip to content
jshacks.dev
Async

async/await in JavaScript: The Complete Guide

A complete guide to async and await in JavaScript on Node.js 24: what they do, error handling, loops, parallel work, top-level await, timing and pitfalls.

29 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Apache Kafka, Redis and Node.js logos.

async and await are the most useful syntax JavaScript added in the last decade, and also one of the easiest to use while misunderstanding. They let you write code that waits for slow operations in the same top-to-bottom style as ordinary code, with try/catch for errors and loops for repetition. They do not change what the code does. Underneath, every async function returns a promise, every await is a promise handler in disguise and the timing rules of the event loop apply exactly as before. That gap between how the code reads and how it runs is where nearly every async/await bug lives: the await that was missing, the loop that ran in sequence when it could have run together, the forEach that did not wait, the try block that did not catch, the function that blocked the thread although it was marked async. This guide covers the whole feature on Node.js 24 and in current browsers. It starts with what the two keywords do, then works through the return value of an async function, error handling, sequences and loops, running work in parallel, the timing of the resume, top-level await, async in classes and callbacks, testing, debugging and the mistakes to avoid. Every example shows the output it prints.

The guide assumes you know what a promise is. If you do not, read the promises guide first, because everything here is a consequence of it.

What the two keywords do

async is a modifier on a function. It does two things: it makes the function return a promise, and it allows await inside its body. await is an operator that you can write in front of an expression inside an async function. It does four things: it converts the value of the expression to a promise, it suspends the function until that promise settles, it hands control back to whoever called the function and, when the promise settles, it resumes the function with the fulfilled value as the result of the expression, or throws the rejection reason at that point.

JavaScript
const wait = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));

async function main() {
  console.log("1: before the first await");
  const value = await wait(10, "result");
  console.log("3: after the await, got", value);
  return "main finished";
}

const promise = main();
console.log("2: main returned a promise, the caller continues");
console.log("4:", await promise);
Text
1: before the first await
2: main returned a promise, the caller continues
3: after the await, got result
4: main finished

Line 1 printed before line 2. The body of an async function runs synchronously, on the caller's stack, until it reaches its first await. At that point the function is suspended and the caller gets its promise back. Line 3 ran ten milliseconds later, when the timer fired and the promise settled. This ordering, with the code before the first await running now and the code after it running later, is the single most useful fact about the feature, and it is the reason async does not by itself make anything non-blocking.

await suspends the function, not the thread. While main waits, the thread is free to run anything else: other callbacks, other requests, other async functions. The suspension is cheap, because the engine saves the function's local variables and the position in its code, and restores them on resume, with no thread involved.

Why it exists: reading the same code three ways

The best way to see what async/await buys is to write the same task three times. The task: read a configuration file, use it to find a user file, read that, and print the user's name.

JavaScript
import { readFile } from "node:fs";
import { readFile as readFilePromise } from "node:fs/promises";

// 1. callbacks
readFile("config.json", "utf8", (error, configText) => {
  if (error) return console.log("failed:", error.code);
  const config = JSON.parse(configText);

  readFile(config.userFile, "utf8", (error2, userText) => {
    if (error2) return console.log("failed:", error2.code);
    console.log("callback:", JSON.parse(userText).name);
  });
});

// 2. promises
readFilePromise("config.json", "utf8")
  .then((text) => readFilePromise(JSON.parse(text).userFile, "utf8"))
  .then((text) => console.log("promise:", JSON.parse(text).name))
  .catch((error) => console.log("failed:", error.code));

// 3. async and await
async function showUser() {
  try {
    const config = JSON.parse(await readFilePromise("config.json", "utf8"));
    const user = JSON.parse(await readFilePromise(config.userFile, "utf8"));
    console.log("await:", user.name);
  } catch (error) {
    console.log("failed:", error.code);
  }
}

showUser();
Text
callback: Ada
promise: Ada
await: Ada

This assumes a config.json containing {"userFile": "user.json"} and a user.json with a name of Ada, and the three results may print in any order, since the reads race. The third version reads like the synchronous code you would write if reading a file were instant. The variables from the first step are in scope in the second, with no nesting, and one try/catch handles every failure, including the one from JSON.parse. That readability is the whole point, and it is why async/await replaced most promise chains in application code.

What an async function returns

An async function always returns a promise, whatever its body does. A returned value fulfills the promise, a thrown error rejects it and a returned promise is followed, so you never get a promise of a promise.

JavaScript
async function five() {
  return 5;
}

async function boom() {
  throw new Error("failed inside");
}

console.log(five());
console.log(await five());

const rejected = boom();
console.log(rejected instanceof Promise);
await rejected.catch((error) => console.log("caught:", error.message));
Text
Promise { 5 }
5
true
caught: failed inside

The call to boom() did not throw. It returned a rejected promise, and the error surfaced only when something handled the rejection. This is a feature: the function has one failure channel, and callers who use .catch() or try/await see every failure, including the ones from argument validation at the top of the body. A plain function that returns a promise but validates its arguments synchronously can throw before it returns anything, and a caller who wrote .catch() misses it. Declaring the function async removes that trap.

The post on how async functions return promises goes through the rule in detail, including the Promise { 5 } you will see in logs when you forget an await, and the fact that each call creates a new promise, so two calls never return the same object.

What await does under the hood

Understanding the mechanism of await makes the timing predictable. When the engine evaluates await expression, it converts the result to a promise, as Promise.resolve would, suspends the function and attaches the rest of the function as a handler on that promise. When the promise settles, a microtask is queued to resume the function. Two consequences follow, and both surprise people the first time.

First, await always yields, even when the operand is not a promise or is already settled. The resume always goes through the microtask queue, so code after an await never runs synchronously.

JavaScript
async function demo() {
  console.log("A: before await");
  await 5;
  console.log("C: after await");
}

demo();
console.log("B: after calling demo");
Text
A: before await
B: after calling demo
C: after await

Second, the continuation runs as a microtask, so it runs before any timer, input event or rendering that is waiting. Two async functions that alternate through await take turns one step at a time.

JavaScript
async function worker(name) {
  console.log(name, "step 1");
  await null;
  console.log(name, "step 2");
  await null;
  console.log(name, "step 3");
}

worker("A");
worker("B");
console.log("main done");
Text
A step 1
B step 1
main done
A step 2
B step 2
A step 3
B step 3

You should not write programs that depend on this exact interleaving, but you should understand it, since it explains the logs of concurrent code. The post on how await works under the hood covers the steps, the cost of awaiting a native promise as opposed to a thenable and the way the engine rebuilds stack traces across the suspension.

A rewrite of await as then makes the transformation visible. A function with two awaits is a function whose second half is nested inside the first handler, with the local variables carried along.

JavaScript
const wait = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));

async function withAwait() {
  const a = await wait(5, "a");
  const b = await wait(5, "b");
  return a + b;
}

function withThen() {
  return wait(5, "a").then((a) => wait(5, "b").then((b) => a + b));
}

console.log(await withAwait(), await withThen());
Text
ab ab

Error handling with try, catch and finally

When an awaited promise rejects, the function resumes by throwing the reason at the await expression, and ordinary try/catch/finally works. This is the biggest practical benefit after readability, since one handler covers a whole sequence.

JavaScript
async function risky() {
  try {
    await Promise.reject(new Error("remote failed"));
    console.log("not printed");
  } catch (error) {
    console.log("caught at the await:", error.message);
    return "fallback";
  } finally {
    console.log("finally runs");
  }
}

console.log(await risky());
Text
caught at the await: remote failed
finally runs
fallback

Three points deserve attention. The first is that try/catch catches only what is awaited inside the try block. A promise created inside the block and not awaited rejects later, after the block has ended, and is unhandled.

JavaScript
async function failing() {
  throw new Error("failed inside");
}

async function missingAwait() {
  try {
    failing(); // not awaited
    console.log("try block ended without catching anything");
  } catch {
    console.log("never reached");
  }
}

process.once("unhandledRejection", (reason) => {
  console.log("unhandled rejection:", reason.message);
});

await missingAwait();
await new Promise((resolve) => setTimeout(resolve, 10));
Text
try block ended without catching anything
unhandled rejection: failed inside

The second is the difference between return promise and return await promise inside a try. A bare return hands the promise out, and the rejection happens after the function has left the try, so the catch does not see it. With return await, the rejection is thrown inside the block.

JavaScript
const failLater = () => Promise.reject(new Error("late failure"));

async function withoutAwait() {
  try {
    return failLater();
  } catch {
    return "handled inside";
  }
}

async function withAwait() {
  try {
    return await failLater();
  } catch {
    return "handled inside";
  }
}

console.log(await withAwait());

try {
  await withoutAwait();
} catch (error) {
  console.log("escaped the try:", error.message);
}
Text
handled inside
escaped the try: late failure

Outside a try, the two forms behave the same for the caller, and a linter rule that forbids return await there is reasonable. Inside one, return await is correct whenever the catch or finally should apply to the returned promise. A related benefit is that return await keeps the function in the async stack trace.

The third point is to keep errors informative as they travel. When you catch an error and throw a different one, pass the original as cause, so both stacks survive.

JavaScript
async function loadUser(id) {
  try {
    await Promise.reject(new Error("connection reset"));
  } catch (cause) {
    throw new Error(`could not load user ${id}`, { cause });
  }
}

try {
  await loadUser(7);
} catch (error) {
  console.log(error.message, "<-", error.cause.message);
}
Text
could not load user 7 <- connection reset

A final habit that pays off is to decide where errors are handled. Low-level functions should let them travel up. One handler at the boundary of the program, such as a request handler or a job runner, should translate them into a response or a retry. A catch in the middle that logs and swallows the error makes a failure invisible to everything above it.

Sequences and loops

A for or for...of loop with await inside runs its iterations one after another, each waiting for the previous one. That is the right behavior when each step depends on the result of the last, or when order matters, or when the receiving service cannot take concurrent requests.

JavaScript
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const order = [];

for (const id of [1, 2, 3]) {
  await wait(10);
  order.push(id);
}

console.log(order);
Text
[ 1, 2, 3 ]

Three ten-millisecond waits cost about thirty. The loop is also the right way to stop early, since break works, and to handle each result as soon as it arrives.

Array methods that take callbacks do not wait. forEach ignores the promises its callback returns, so the loop finishes at once and the work happens later, with errors unhandled.

JavaScript
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

[1, 2, 3].forEach(async (n) => {
  await wait(10);
  console.log("inside forEach callback", n);
});

console.log("after forEach");
await wait(40);
Text
after forEach
inside forEach callback 1
inside forEach callback 2
inside forEach callback 3

The line after the loop printed first. The same applies to map, filter and reduce: they run their callbacks synchronously and collect whatever those return. For map, what comes back is an array of promises, which is useful, because Promise.all can wait for it. For filter and forEach, the promises are ignored or treated as truthy values, which is a bug. A reduce with an async callback works as a sequence if you await the accumulator, though a for...of loop is clearer.

JavaScript
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const doubled = await Promise.all(
  [1, 2, 3].map(async (n) => {
    await wait(10);
    return n * 2;
  }),
);

console.log(doubled);
Text
[ 2, 4, 6 ]

The rule of thumb: use for...of with await when the steps are dependent or ordered, and Promise.all with map when they are independent.

Running work in parallel

Awaiting independent operations one at a time wastes time, since the second does not start until the first finishes. To overlap them, start them all first and await them together.

JavaScript
const wait = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));

let start = Date.now();
const a1 = await wait(30, "a");
const b1 = await wait(30, "b");
const sequential = Date.now() - start;

start = Date.now();
const [a2, b2] = await Promise.all([wait(30, "a"), wait(30, "b")]);
const parallel = Date.now() - start;

console.log(a1 + b1, a2 + b2);
console.log("sequential at least 55 ms:", sequential >= 55);
console.log("parallel under 55 ms:", parallel < 55);
Text
ab ab
sequential at least 55 ms: true
parallel under 55 ms: true

A subtle variation is to start the promises first and await later, which gives the same overlap with a clearer structure when the results are used in different places.

JavaScript
const userPromise = wait(20, { name: "Ada" });
const settingsPromise = wait(20, { theme: "dark" });

const user = await userPromise;
const settings = await settingsPromise;

console.log(user.name, settings.theme);
Text
Ada dark

Both started immediately, since promises are eager, and the two awaits then wait for whichever remains. One hazard here is that if the second promise rejects while the first is still being awaited, the rejection has no handler yet, which may report an unhandled rejection before your code gets to it. Promise.all attaches handlers to all of its inputs at once, so it avoids the problem.

Choosing between the combinators is a question of what a failure should mean. Promise.all rejects on the first failure and is for all-or-nothing work. Promise.allSettled reports every outcome and is for batches where partial results matter. Promise.race takes the first outcome and is the base for timeouts. Promise.any takes the first success and suits redundant sources. They are covered in the guide on asynchronous JavaScript and in a post each, and the common thread is that none of them limits how many operations run at once. If a list can be long, run it through a bounded pool, so that no more than a few operations are in flight.

JavaScript
async function mapLimit(items, limit, worker) {
  const results = new Array(items.length);
  let next = 0;

  async function lane() {
    while (next < items.length) {
      const index = next++;
      results[index] = await worker(items[index]);
    }
  }

  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, lane));
  return results;
}

let running = 0;
let peak = 0;

const out = await mapLimit([1, 2, 3, 4, 5, 6], 2, async (n) => {
  running += 1;
  peak = Math.max(peak, running);
  await new Promise((resolve) => setTimeout(resolve, 5));
  running -= 1;
  return n * 10;
});

console.log(out, "peak:", peak);
Text
[ 10, 20, 30, 40, 50, 60 ] peak: 2

Race conditions across await

Every await is a gap. While your function is suspended, other code runs, and state that you read before the await may be stale after it. A read-modify-write that spans an await can therefore lose updates, even though no two lines of code ever run at the same instant.

JavaScript
let balance = 100;

async function withdraw(amount) {
  const current = balance; // read
  await new Promise((resolve) => setTimeout(resolve, 5)); // some async check
  balance = current - amount; // write based on a stale read
}

await Promise.all([withdraw(30), withdraw(50)]);

console.log("expected 20, got", balance);
Text
expected 20, got 50

Both calls read 100 before either wrote, and the first withdrawal was lost. The remedies are to keep the check and the action in the same synchronous stretch, with no await between them, to serialize the critical section with a promise-based lock, to tag requests with sequence numbers and discard stale results, and to make operations idempotent. The post on race conditions in single-threaded JavaScript works through five such races.

A related trap is checking a condition, awaiting, and then acting as if the condition still held. If two callers can both pass the check before either acts, you have a bug. Claim the resource before the first await, and release it on failure.

async does not mean non-blocking

An async function that does heavy computation blocks the thread like any other function, because the body runs on the caller's stack until its first await, and a computation has no await to give way at.

JavaScript
async function heavy() {
  let total = 0;
  for (let i = 0; i < 30_000_000; i++) total += i;
  return total;
}

setTimeout(() => console.log("timer"), 0);

const promise = heavy();
console.log("heavy returned a promise");
console.log(await promise);
Text
heavy returned a promise
449999985000000
timer

The loop ran inside the call to heavy(), before it returned, so the timer waited for all of it. Marking a function async changes how its result is delivered and not where its work runs. Heavy work needs a worker thread, or slicing with a macrotask boundary, such as scheduler.yield() in a browser or setImmediate in Node.js, between pieces. Awaiting a resolved promise inside the loop does not help, because microtasks run before timers and input, and the loop never gives way.

The same applies to synchronous APIs in Node.js: readFileSync and its relatives hold the thread, and using them inside an async function is no better than using them anywhere else.

Top-level await

In an ES module, await can appear at the top level, outside any function, which is convenient for scripts and for modules that need a value before they can export anything. A module that awaits delays every module that imports it, because they all wait for it to finish evaluating.

JavaScript
// config.mjs
const response = await Promise.resolve({ port: 8080 });
export const port = response.port;
JavaScript
// main.mjs
import { port } from "./config.mjs";

console.log("port is", port);
Text
port is 8080

Top-level await works in .mjs files or with "type": "module", and not in CommonJS. A require() of a module whose graph contains top-level await throws ERR_REQUIRE_ASYNC_MODULE. Use it for startup configuration and scripts, and avoid slow or failure-prone calls in modules that many others import, since a failure there stops the whole application at load time. Siblings that do not depend on each other evaluate their awaits at the same time, so keep each wait in its own module. The post on top-level await covers the ordering, the exit code for an unsettled await and the dynamic import() alternative.

async in classes, callbacks and iterators

You can mark methods async, including static methods, and getters cannot be. Constructors cannot be async, so provide a static factory when construction needs to wait.

JavaScript
class Cache {
  #store = new Map();

  async get(key, loader) {
    if (!this.#store.has(key)) {
      this.#store.set(key, loader(key));
    }
    return this.#store.get(key);
  }

  static async create(entries) {
    const cache = new Cache();
    for (const [key, value] of entries) cache.#store.set(key, Promise.resolve(value));
    return cache;
  }
}

const cache = await Cache.create([["a", 1]]);
console.log(await cache.get("a"), await cache.get("b", async () => 2));
Text
1 2

Passing an async function as a callback to an API that does not await it, such as an event listener, setTimeout, forEach or Array.prototype.sort, is a recurring source of unhandled rejections and silently ignored work. If a library calls your callback and ignores the return value, a throw inside an async callback becomes an unhandled rejection and not a visible crash in the right place. Handle errors inside such callbacks yourself, or wrap them in a helper that catches and reports. For events specifically, Node.js has new EventEmitter({ captureRejections: true }), which routes a rejected handler to the emitter's error event.

async function* declares an async generator, which yields values and can await between them, consumed with for await...of. It is the tool for sequences that arrive over time, such as pages of an API or lines of a file, and its behavior is the subject of the post on async iterators.

JavaScript
async function* countdown(from) {
  for (let n = from; n > 0; n--) {
    await new Promise((resolve) => setTimeout(resolve, 5));
    yield n;
  }
}

for await (const n of countdown(3)) console.log(n);
Text
3
2
1

Timeouts and cancellation

An await waits as long as the promise takes, which may be forever. Give every operation that touches the network, the disk or another process a deadline. The modern way is to pass an AbortSignal to the operation, and AbortSignal.timeout(ms) creates one that aborts itself with a TimeoutError.

JavaScript
import { setTimeout as sleep } from "node:timers/promises";

try {
  await sleep(1000, "finished", { signal: AbortSignal.timeout(20) });
} catch (error) {
  console.log(error.name);
}
Text
TimeoutError

Where an API takes no signal, race the promise against a timer and clear the timer afterwards, accepting that the slow work continues unseen. The full treatment of AbortController, combined signals and writing your own cancellable functions is in the cancellation guide. An important detail for await is that an abort appears as a rejection, usually named AbortError, so catch blocks should distinguish it from real failures and treat it as an expected outcome.

Testing async code

Make every test function async and await the work, or the runner finishes before your assertions run, and the test passes without checking anything. Use assert.rejects for expected failures, which fails the test if the promise fulfills.

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

async function parse(text) {
  return JSON.parse(text);
}

test("parses valid input", async () => {
  assert.deepEqual(await parse('{"a":1}'), { a: 1 });
});

test("rejects invalid input", async () => {
  await assert.rejects(parse("{bad"), SyntaxError);
});
Text
āœ” parses valid input
āœ” rejects invalid input

Avoid real waits. A test that sleeps for 100 ms and then asserts is flaky on a loaded machine. Wait on something you control, such as a deferred from Promise.withResolvers(), and use fake timers to move time forward by hand. Assert on order and outcome kinds, not durations, and check the unhappy paths: a failure, a slow dependency and one that never answers. When a test runner hangs after the last test, a timer or socket was left open, and clearing it is part of cleanup.

Debugging async code

When the order of output is not what you expect, label the scheduling points and read the sequence. Most surprises are an await assumed to be a task when it is a microtask, or a missing await that let code run before a result existed. Stack traces after an await are rebuilt by the engine from the chain of async functions that are awaiting each other, and they show at async name lines. The rebuild stops at callbacks, timers and promise plumbing that does not use await, so keep important paths in async and await, name your functions and attach a cause when you rethrow. Raise Error.stackTraceLimit while debugging if the trace is cut off. The post on async stack traces explains the details.

To find dropped promises, enable a linter rule for floating promises, and run tests with node --unhandled-rejections=strict so that a rejection nobody handled fails the run and points to its origin. In a browser, the debugger's async stack option stitches frames together across await, and the Performance panel shows which task held the thread when a page froze. In Node.js, monitorEventLoopDelay from node:perf_hooks measures how late the loop is running, which is the number to watch when something blocks.

Mistakes that appear everywhere

  • **A missing await.** The variable holds a promise, and property reads on it return undefined. Lint for floating promises.

  • **forEach with an async callback.** The loop does not wait. Use for...of, or Promise.all with map.

  • **await in a loop of independent work.** It serializes what could overlap. Start the work first and await together.

  • **A bare return promise inside try.** The catch misses the rejection. Use return await.

  • **A catch that swallows the error.** Rethrow, or return a deliberate fallback, and log with context.

  • **Unbounded Promise.all.** A promise per item for thousands of items overwhelms the service. Bound the concurrency.

  • **A race across await.** State read before the gap may be stale after it. Keep check and action together, or serialize.

  • **Heavy work in an async function.** It blocks the thread. Use a worker or slice the work.

  • **An async callback where nobody awaits.** Event handlers, timers and forEach ignore the returned promise, so errors go unhandled.

  • No deadline. An await on a call that never answers hangs the function forever. Add a timeout.

When not to use async and await

Plain functions are better for work that is synchronous and cheap. Marking such a function async allocates a promise per call and delays the caller by a microtask, for no benefit. Event listeners, which fire many times, are better as callbacks, and sequences that arrive over time suit async iterators or streams. Performance-critical inner loops should stay synchronous, with await at the edges of the loop. And a function that must produce its result immediately, such as a getter, a comparator or a render function, cannot be async at all.

A mental model that holds up

The most reliable way to think about an async function is as a function that can be paused at every await, with its whole state saved, and resumed later by the event loop. Picture the body cut into segments at each await. The first segment runs when you call the function. Every later segment runs as a separate microtask, once the promise that precedes it settles. Between segments, the function is not on the call stack at all, and anything can run: other functions, timers, the same function called again. That picture answers most questions in advance.

Why can two calls to the same function interleave? Because each call is its own suspended state machine, and their segments alternate on the microtask queue. Why does a try/catch around an un-awaited call catch nothing? Because the call returns at the first await and the try block is long over when the failure arrives. Why does a variable shared between calls cause bugs? Because the segments of different calls interleave around it. Why can a long loop inside an async function freeze the page? Because a segment is just ordinary code, and a segment with a long loop holds the thread for the whole of the loop.

The same picture explains cost. A suspension and a resume are cheap compared with an operating system thread, which is what makes it practical to have thousands of async functions waiting at once. Each suspended function holds its local variables in memory, so ten thousand pending calls hold ten thousand sets of locals. That is usually fine, and it means that unbounded fan-out costs memory as well as load on whatever you call.

Writing readable async code

Because async/await makes asynchronous code look synchronous, it invites the same style rules, and a few extra ones.

Keep functions short and give each a single level of abstraction. A function that fetches, validates, transforms and saves is easier to read as four small async functions that a fifth calls in order, since each await line then reads like a sentence: fetch the record, validate it, transform it, save it. Name functions for what they produce, and prefer names that make the asynchrony obvious when it is not implied by the verb, such as loadUser and saveDraft, so that a reader sees a promise and knows an await belongs in front.

Await at the point of use, not earlier. If a value is needed three lines later, start the operation now, and await it when you need it, so independent work overlaps. If a value is needed immediately, await at once. A line such as const [user, settings] = await Promise.all([...]) groups independent work and makes the dependency structure visible.

Prefer early returns and guard clauses to deep nesting. An async function with a try around everything, then an if inside it, then another await inside that, loses the flat shape that is the reason for using the syntax. Move the failure handling to a small helper, or to a boundary higher up, and keep the happy path straight.

Do not mix styles in one function without a reason. A function that awaits in one place and uses .then in another is harder to follow than either style alone. The exception is .catch on a single call to supply a fallback, such as await load().catch(() => null), which is compact and clear.

JavaScript
async function loadOptional(loader) {
  return (await loader().catch(() => null)) ?? "default";
}

console.log(await loadOptional(async () => "value"));
console.log(await loadOptional(async () => {
  throw new Error("failed");
}));
Text
value
default

Finally, resist wrapping every await in its own try/catch. A catch per line scatters error handling and tends to swallow failures. Group a sequence under one try when the right response to any failure is the same, and use a separate one only where a specific step has a specific recovery.

Moving from promise chains to async and await

Converting a chain to async/await is mostly mechanical. Each then handler becomes the code after an await, a catch becomes a catch block, and a finally becomes a finally block. The care goes into three places.

First, a handler that returned a value without waiting becomes a plain assignment, and a handler that returned a promise becomes an await. Do not add await to synchronous values, which only adds a pointless suspension.

Second, nested chains that exist because a later step needed an earlier value flatten out, since the earlier value stays in scope. This is the biggest readability gain.

Third, watch the error semantics. In a chain, then(a).catch(b) handles errors from a, and in try { await x; a(); } catch { b(); } the same holds, but a then(a, b) with both arguments does not handle errors from a, and has no direct equivalent. If you rely on that subtle behavior, restructure rather than translating line by line.

JavaScript
// before
function loadSummary(id) {
  return fetchUser(id)
    .then((user) => fetchPosts(user.id).then((posts) => ({ user, posts })))
    .then(({ user, posts }) => `${user.name} has ${posts.length} posts`)
    .catch(() => "unavailable");
}

// after
async function loadSummaryAsync(id) {
  try {
    const user = await fetchUser(id);
    const posts = await fetchPosts(user.id);
    return `${user.name} has ${posts.length} posts`;
  } catch {
    return "unavailable";
  }
}

After converting, look for sequences of independent awaits and combine them with Promise.all, since the mechanical translation of a chain preserves its sequential order, including steps that never needed it. A chain that fetched two unrelated resources one after the other was slow before and is slow after, and the new syntax makes the waste easy to see.

What it costs

Every await adds a suspension and a resume, and every async call allocates a promise. For code that waits on a network or a disk, the cost is invisible next to the wait. For code that never waits, such as a function that is async for uniformity but only does arithmetic, it is pure overhead, and in a hot loop that runs millions of times it shows. The answer is not to avoid async, since readable code matters more than saving a few microseconds in most programs, but to keep synchronous work synchronous and put the await at the edges of the loop and not inside it.

Compared with promise chains, the two styles cost about the same, since they produce the same microtasks. Older engines took extra ticks to await a native promise, a difference that was removed in the language specification years ago, and current engines handle it in one tick. Avoid comparing performance from memory or from old write-ups. If the speed of an async function matters to you, measure your real workload.

There is a real memory consideration worth knowing. A suspended async function keeps its local variables alive, including large buffers, until it finishes. A function that reads a large file into memory and then awaits a slow upload, with the buffer in scope, holds the buffer for the whole upload. Narrow the scope of large values, or set them to undefined when done, and prefer streams for data that does not need to be in memory at once.

A few questions people ask

*Should I await a value that is not a promise?* It works, and it yields once, which is rarely what you want. Use await only on promises. A linter rule can flag the rest.

*Can I use await in a callback?* Only if the callback itself is async, and the code that calls it must be prepared to ignore or handle the returned promise. Many APIs, including event emitters and array callbacks, do not.

*Is async an arrow function thing?* No, it works on function declarations, expressions, arrow functions and methods. An immediately invoked async arrow, (async () => { ... })(), was the old way to use await at the top level of a script, and top-level await in modules has replaced it where you can use modules.

*What does await do with a rejected promise that I already handled?* It still throws, since await observes the outcome itself. Handling a promise elsewhere does not stop an await on it from throwing.

*Why does my async function seem to run twice?* It is called twice, usually from two places, such as two event handlers or a retry. Because each call is independent and calls interleave, guard shared state, or share the in-flight promise so that duplicate callers join one operation.

*Can I await in a finally block?* Yes. The function waits for it before continuing, and an error thrown in finally replaces any earlier one.

*How do I run something after an async function without awaiting it?* Attach then or finally to its promise, and give it a catch so that a failure is handled, or mark the call as intentionally fire-and-forget with a handler that logs.

Applying it: a small service function, end to end

To see the pieces working together, consider a function that a web service might contain: look up an order, fetch its customer and its line items at the same time, apply a deadline and return a summary or a clear error. It uses nearly everything in this guide, and reading it slowly is a good check that each part makes sense.

JavaScript
import { setTimeout as sleep } from "node:timers/promises";

const db = {
  async order(id, { signal }) {
    await sleep(10, null, { signal });
    if (id !== 1) throw Object.assign(new Error("order not found"), { code: "E_NOT_FOUND" });
    return { id, customerId: 7, lineIds: [1, 2] };
  },
  async customer(id, { signal }) {
    await sleep(15, null, { signal });
    return { id, name: "Ada" };
  },
  async lines(ids, { signal }) {
    await sleep(15, null, { signal });
    return ids.map((id) => ({ id, price: id * 10 }));
  },
};

async function orderSummary(orderId, { timeoutMs = 100 } = {}) {
  const signal = AbortSignal.timeout(timeoutMs);

  try {
    const order = await db.order(orderId, { signal });

    const [customer, lines] = await Promise.all([
      db.customer(order.customerId, { signal }),
      db.lines(order.lineIds, { signal }),
    ]);

    const total = lines.reduce((sum, line) => sum + line.price, 0);
    return `${customer.name} owes ${total} for order ${order.id}`;
  } catch (error) {
    if (error.name === "TimeoutError") {
      throw new Error(`order ${orderId} timed out`, { cause: error });
    }
    throw error;
  }
}

console.log(await orderSummary(1));

await orderSummary(2).catch((error) => console.log(error.code, "-", error.message));
await orderSummary(1, { timeoutMs: 5 }).catch((error) => console.log(error.message));
Text
Ada owes 30 for order 1
E_NOT_FOUND - order not found
order 1 timed out

Walk through it. The function creates one deadline signal and passes it to every call, so the whole operation shares one time limit, and not one per step. The order lookup has to come first, since the next calls need its fields, so it is awaited alone. The customer and the lines are independent, so they start together and are awaited with Promise.all, and the second step takes as long as the slower of the two and not the sum. Errors are handled once, at the bottom: a timeout is translated into a clearer message with the original attached as the cause, and every other error, such as the not-found error with its code, travels up untouched for the caller to decide what to do. No call is left dangling, no await is missing and the deadline stops the work of every step that listens to the signal, not only the waiting.

This is the shape that most well-structured async code takes: dependent steps in sequence, independent ones together, one signal for the deadline, errors handled at a boundary and information preserved as they travel. When code you write looks very different, such as a loop that awaits independent calls one by one or a catch in every function that logs and returns null, it is worth a second look.

One more thing about the example is worth pointing out. Every database helper accepts the same { signal } option, and the summary function does not know or care how each one uses it. That uniformity is what makes the pattern scale: a new helper that follows the convention gets deadlines and cancellation for free, and a caller higher up, such as an HTTP handler that wants to stop work when the client disconnects, can combine its own signal with the timeout using AbortSignal.any. Write your own async functions to accept a signal from the start, since adding it later means touching every call site. The same advice applies to returned values: return plain data, or throw an Error with a code, so that callers can branch on facts and not on message text.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.