The Complete Guide to Asynchronous JavaScript
A complete guide to asynchronous JavaScript on Node.js 24 and browsers, from the event loop and promises to async await, cancellation, streams and patterns.

Asynchronous code is where most JavaScript bugs live, and it is also where most of the language's power is spent. A page that fetches data while you scroll, a server that handles ten thousand connections on one thread, a build tool that reads a thousand files at once, a script that retries a flaky call with a growing delay: all of them depend on the same small set of ideas. Those ideas are easy to use and surprisingly hard to hold in your head all at once, which is why asynchronous bugs feel different from other bugs. They depend on order, they depend on timing, and they often disappear when you add a log line. This guide puts the whole subject in one place, on Node.js 24 and current browsers, and builds from the runtime model upward: how a single thread can wait for many things, what callbacks, promises and async/await each add, how to run work together without overwhelming anything, how to cancel, how to handle errors, how to stream data and how to test and debug the result. It is long on purpose. Each section stands on its own, and each ends where the next one begins, so you can read it through once and return to the parts you need.
The examples are written to be read in order, and each one shows the output it produces. Where a detail varies between runtimes, the text says so, and where a topic has its own deeper post, there is a link. If you only have ten minutes, read the first two sections, the decision guide near the end and the list of mistakes. If you have an hour, read everything.
What asynchronous means, and why JavaScript needs it
A synchronous program does one thing at a time and waits for each thing to finish. An asynchronous program starts something that will take a while, goes on with other work and handles the result when it arrives. The reason JavaScript leans so heavily on the second style is its execution model. Your code runs on a single thread, with one call stack, and while a function is running nothing else in your program can run. If that function waited for a network response by sitting idle, the whole page, or the whole server, would sit idle with it.
The solution is to split the work between your code and the environment around it. When you ask for a network request, a timer or a file read, the browser or Node.js does the waiting outside your thread, and your code continues. When the operation finishes, the environment places a task in a queue, and your thread picks it up as soon as it is free. The effect is that waiting costs nothing, and the thread is only ever used for actual computation.
console.log("1: script starts");
setTimeout(() => {
console.log("3: the timer callback runs");
}, 0);
console.log("2: script ends");1: script starts
2: script ends
3: the timer callback runsThe timer was set to zero milliseconds, and its callback still ran last. setTimeout does not run the function; it hands it to the environment and returns immediately. The environment queues the callback when the delay expires, and your thread runs it only after the current script has finished. That ordering, current code first and queued callbacks afterward, is the first rule of asynchronous JavaScript, and everything in this guide is a consequence of it.
Two terms are often confused, so fix them now. Concurrency means several tasks are in progress during the same period, with their work interleaved. Parallelism means several tasks execute at the same instant on different processor cores. JavaScript's main thread gives you concurrency and never parallelism: one piece of your code runs at a time, but while one operation waits, another can run. True parallelism arrives only with worker threads, which the section on concurrency covers.
It follows that asynchronous code speeds up waiting and nothing else. If a function spends a second computing, making it asynchronous does not make it faster, and during that second the thread is held. Keep that distinction in mind whenever someone suggests "just make it async" as a performance fix. It is a fix for blocking on slow external operations, and it is no help for slow computation.
The runtime model: stack, queues and the event loop
To predict the order in which asynchronous code runs, you need a small mental model with four parts.
The call stack holds the functions that are currently running. When a function is called, it goes on the stack, and when it returns, it comes off. The stack must be empty before anything else can run.
The task queue, sometimes called the macrotask queue, holds callbacks waiting to run: timer callbacks, input and output callbacks, user events and messages. Each is one unit of work, which the event loop takes when the stack is empty.
The microtask queue holds smaller, more urgent callbacks: promise reactions, the continuation after an await, and functions passed to queueMicrotask. The rule that matters is that the microtask queue is emptied completely after the current task finishes and before the next task begins.
The event loop is the process that connects them. It picks a task, runs it to completion, drains the microtask queue and, in a browser, may render, then repeats.
console.log("script start");
setTimeout(() => console.log("timeout (task)"), 0);
Promise.resolve()
.then(() => console.log("promise 1 (microtask)"))
.then(() => console.log("promise 2 (microtask)"));
queueMicrotask(() => console.log("queueMicrotask (microtask)"));
console.log("script end");script start
script end
promise 1 (microtask)
queueMicrotask (microtask)
promise 2 (microtask)
timeout (task)Walk through it with the model. The script itself is the first task. It runs both console.log lines and schedules the timer, the promise reaction and the microtask. When the script finishes, the stack is empty, so the engine drains the microtask queue: first the promise reaction, then the queueMicrotask callback, which was queued second, and then the second promise reaction, which was queued only when the first one finished. Only then does the loop take the next task, the timer callback.
Two consequences are worth stating plainly. A promise callback always beats a zero-delay timer, because microtasks run before the next task. And a microtask that keeps queueing another microtask can starve the loop, since the queue must be empty before anything else runs, so timers, input and rendering wait. The full treatment of this is in the event loop guide, and the details of the two queues are in the post on microtasks and macrotasks.
Node.js has a slightly richer loop with named phases, for timers, pending callbacks, polling for input and output, check callbacks from setImmediate and close callbacks, and a separate process.nextTick queue that runs even before promise microtasks. Browsers add a rendering step between tasks. The principle is the same in both: tasks one at a time, microtasks between them.
Callbacks: the original mechanism
A callback is a function you pass to another function to be called later. It is the oldest asynchronous mechanism in JavaScript and the base that everything else is built on. In Node.js, the convention is error-first: the callback receives an error, or null, as its first argument and results after that.
import { readFile } from "node:fs";
readFile("package.json", "utf8", (error, text) => {
if (error) {
console.log("failed:", error.code);
return;
}
console.log("read", text.length > 0 ? "some text" : "an empty file");
});
console.log("request sent");request sent
read some textThis assumes a package.json in the working directory. The line after the call printed first, because readFile returned at once and the callback ran later. The contract of an error-first callback is worth learning exactly: the callback is the last argument, the error is its first, and it is called once. The details, and the ways people break them, are in the post on error-first callbacks.
Callbacks work well for events that happen repeatedly, such as clicks and incoming messages, and for simple one-step operations. They work poorly for sequences. When each step depends on the previous result, the next step goes inside the previous callback, and the code drifts to the right in what is called callback hell. The nesting is not the real problem. The real problems are that error handling must be repeated at every level, that a throw inside an asynchronous callback escapes any try/catch around the original call, and that a missing return after an error branch can call the callback twice. The post on callbacks and callback hell shows each of these and the ways out.
try {
setTimeout(() => {
throw new Error("thrown later");
}, 0);
} catch {
console.log("never reached");
}The try block finished long before the timer fired, so the throw happens in a fresh stack with nothing to catch it, and the process reports an uncaught exception. This is the central weakness of callbacks and the main reason promises were added. Promises give asynchronous operations a result you can hold, pass around, combine and attach error handling to.
Promises: a value that arrives later
A promise is an object that stands for a result that does not exist yet. It starts pending and then becomes either fulfilled, with a value, or rejected, with a reason. Once settled it never changes. You attach functions with then, catch and finally, and they run as microtasks.
const wait = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
wait(20, "first")
.then((value) => {
console.log("got", value);
return wait(10, "second");
})
.then((value) => console.log("got", value))
.catch((error) => console.log("failed:", error.message))
.finally(() => console.log("done either way"));
console.log("chain built");chain built
got first
got second
done either wayThree rules explain nearly every promise behavior, and each has its own post. A promise settles at most once, and its first outcome is final (promise states). The function you pass to new Promise runs immediately and synchronously, so creating a promise starts the work. And then always returns a new promise, whose outcome depends on what your handler returns or throws (chaining).
The third rule is the one that makes chains work. If a handler returns a plain value, the next promise is fulfilled with it. If a handler returns a promise, the chain waits for it and takes its outcome. If a handler throws, the next promise is rejected, and the rejection skips every following then until it meets a catch. A catch that returns normally recovers the chain, and one that rethrows keeps it failing.
Promise.resolve("start")
.then((value) => {
throw new Error(`failed after ${value}`);
})
.then(() => console.log("skipped"))
.catch((error) => {
console.log("caught:", error.message);
return "recovered";
})
.then((value) => console.log("continuing with", value));caught: failed after start
continuing with recoveredThe most common promise bug is a missing return inside a then. Without it, the handler gives back undefined, the next step runs at once with undefined, and the work that was started is abandoned, with any failure becoming an unhandled rejection. The second most common is nesting a then inside a then instead of returning the inner promise, which breaks the error path.
You create promises from callback APIs by wrapping them once, in one place.
import { readFile } from "node:fs";
function readText(path) {
return new Promise((resolve, reject) => {
readFile(path, "utf8", (error, text) => {
if (error) reject(error);
else resolve(text);
});
});
}
console.log((await readText("package.json")).length > 0);trueFor error-first callbacks, util.promisify does the same job, and most of the Node.js standard library now ships promise versions in modules such as node:fs/promises and node:timers/promises. When you have a choice, use those. The static helpers Promise.resolve and Promise.reject create settled promises, and they have a few rules of their own, described in that post.
async and await: promises that read like normal code
async/await is syntax over promises. A function marked async always returns a promise: a returned value fulfills it, and a thrown error rejects it. Inside such a function, await suspends that function until a promise settles and then continues with the result, or throws the rejection, so ordinary try/catch works.
const wait = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function main() {
try {
const first = await wait(20, "first");
console.log("got", first);
const second = await wait(10, "second");
console.log("got", second);
throw new Error("something went wrong");
} catch (error) {
console.log("caught:", error.message);
} finally {
console.log("cleanup");
}
}
main();
console.log("main called");main called
got first
got second
caught: something went wrong
cleanupThe function ran synchronously until its first await, then returned control to the caller, which printed the line after the call. The rest of the function ran later, one await at a time. Understanding what await does under the hood explains the timing of everything built on it: it converts the operand to a promise, suspends the function, returns control and resumes in a microtask. That is covered in detail in how await works, and how async functions return promises covers the return side.
Three details are worth knowing from the start. Code before the first await runs synchronously on the caller's stack, so heavy work there blocks like any other. Inside a try block, return await somePromise lets the catch handle a rejection, while a bare return somePromise does not. And a loop with await inside runs its steps one after another, which is correct when each step depends on the last and slow when the steps are independent.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function sequential(items) {
const results = [];
for (const item of items) {
await wait(10);
results.push(item * 2);
}
return results;
}
async function together(items) {
return Promise.all(
items.map(async (item) => {
await wait(10);
return item * 2;
}),
);
}
console.log(await sequential([1, 2, 3]));
console.log(await together([1, 2, 3]));[ 2, 4, 6 ]
[ 2, 4, 6 ]Both give the same answer. The sequential version takes about three waits, and the second about one. Use the first when order matters or each step needs the previous result, and the second when the steps are independent. At the top level of an ES module, you can await directly, without a wrapper function, which is described in top-level await, along with the way it delays importers.
A common beginner trap is forEach with an async callback. forEach ignores the promises its callback returns, so the loop finishes immediately, and the awaited work happens later, with any errors going unhandled. Use for...of with await for sequence, or Promise.all with map for parallel work.
Running things together: the promise combinators
Four static methods combine several promises into one. They answer different questions, and choosing the right one is mostly a matter of deciding what should happen when one of the promises fails or finishes early.
Promise.all waits for every promise to fulfill and gives you the results in input order, or rejects at the first rejection. It is for all-or-nothing work, where one failure makes the others worthless (details). Promise.allSettled waits for every promise to finish and reports each outcome as a status object, never rejecting, which fits batch work where partial results matter (details). Promise.race settles with whichever promise settles first, success or failure, and is the usual base for timeouts (details). Promise.any fulfills with the first success and rejects with an AggregateError only if all fail, which suits redundant sources (details).
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const failAfter = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
console.log("all:", await Promise.all([delay(20, "a"), delay(10, "b")]));
console.log(
"allSettled:",
(await Promise.allSettled([delay(10, "a"), failAfter(5, "x")])).map((r) => r.status),
);
console.log("race:", await Promise.race([delay(30, "slow"), delay(10, "fast")]));
console.log("any:", await Promise.any([failAfter(5, "x"), delay(15, "ok")]));all: [ 'a', 'b' ]
allSettled: [ 'fulfilled', 'rejected' ]
race: fast
any: okOne thing none of them does is limit concurrency. By the time you call a combinator, every promise in the list is already running, so a list of five thousand requests means five thousand requests in flight. The section on patterns shows how to run a bounded number at a time. Another thing none of them does is cancel the losers: after race or any settles, the other work continues.
Two newer helpers round out the toolbox. Promise.withResolvers() returns a promise together with its resolve and reject functions, for the case where the code that creates a promise is not the code that settles it (details). Promise.try(fn) calls a function that may be synchronous or asynchronous and always returns a promise, turning a synchronous throw into a rejection (details).
Handling errors in asynchronous code
Errors in asynchronous code fail in a way that is easy to miss, because the code that detects the problem is not on the stack of the code that started the operation. Four rules cover almost everything.
First, a rejection must be handled somewhere. A rejected promise with no handler is an unhandled rejection, and on Node.js 15 and later the default is to crash the process, with browsers logging an error and firing an unhandledrejection event. The post on unhandled rejections covers how each runtime reports them and how to find the source.
Second, await inside try is what makes try/catch work for asynchronous failures. Without the await, the call returns a promise, the try block ends and the rejection arrives later with no handler.
async function failing() {
throw new Error("failed inside");
}
async function missingAwait() {
try {
failing(); // not awaited
console.log("try block finished without catching");
} catch {
console.log("never reached");
}
}
async function withAwait() {
try {
await failing();
} catch (error) {
console.log("caught:", error.message);
}
}
process.once("unhandledRejection", (reason) => {
console.log("unhandled rejection:", reason.message);
});
await missingAwait();
await withAwait();
await new Promise((resolve) => setTimeout(resolve, 10));try block finished without catching
caught: failed inside
unhandled rejection: failed insideThird, reject and throw Error objects, never strings. An Error carries a stack trace and a message, and since ES2022 it can carry a cause, so when you catch an error and throw a more specific one, attach the original with new Error("could not load user", { cause }). A bare rethrow of a new error discards the first stack, which is often the only one that names the failing line. The post on async stack traces explains why traces break after an await and how engines rebuild them.
Fourth, decide where errors are handled, and do it once. Low-level functions should let errors travel up, and one handler near the boundary of the program, such as a request handler, a job runner or the entry point, should translate them into a response, a retry or a log entry. A catch that logs and swallows the error in the middle of a call tree makes a failure invisible to everything above it.
Cancellation and timeouts
Promises cannot be cancelled. Once an operation starts, the promise that represents it has no stop button, and if you stop caring about the result the work continues. The platform's answer is AbortController, which gives you a controller you hold and a signal you pass to the operation. Calling controller.abort() marks the signal aborted and fires an event, and cooperating code stops. fetch, the promise APIs of node:fs, node:timers/promises, child_process, streams and many libraries accept a signal option.
import { setTimeout as sleep } from "node:timers/promises";
const controller = new AbortController();
setTimeout(() => controller.abort(), 10);
try {
await sleep(1000, "finished", { signal: controller.signal });
} catch (error) {
console.log(error.name);
}AbortErrorThe sleep ended after about ten milliseconds instead of a second, and its timer was cleared. For deadlines, AbortSignal.timeout(ms) creates a signal that aborts itself with a TimeoutError, and AbortSignal.any([a, b]) combines several signals so that the first to abort wins. Together they replace the hand-written timer and listener code that used to surround every cancellable request.
import { setTimeout as sleep } from "node:timers/promises";
const user = new AbortController();
const combined = AbortSignal.any([user.signal, AbortSignal.timeout(20)]);
try {
await sleep(1000, null, { signal: combined });
} catch (error) {
console.log(error.name);
}TimeoutErrorCancellation is cooperative. A function that never looks at its signal cannot be stopped, and an abort does not undo what already happened on the other end: a request aborted midway may have been processed by the server. The full story, including how to write your own cancellable functions, is in the cancellation guide and the posts on AbortController and timeouts and combined signals.
Iterating over values that arrive over time
A promise carries one value. Many sources produce a sequence: pages of an API, lines of a file, chunks of a download, messages on a socket. An async iterator is the protocol for that, and for await...of is the loop that consumes it. The producer is usually an async generator, a function declared async function* that can await and yield.
async function* pages() {
for (let page = 1; page <= 3; page++) {
await new Promise((resolve) => setTimeout(resolve, 5));
yield [`item ${page}a`, `item ${page}b`];
}
}
for await (const items of pages()) {
console.log(items);
}[ 'item 1a', 'item 1b' ]
[ 'item 2a', 'item 2b' ]
[ 'item 3a', 'item 3b' ]The generator runs only when the consumer asks for the next value, so a slow consumer slows the producer, which is a natural form of backpressure. Breaking out of the loop early triggers the generator's finally blocks, so cleanup works. The async iterators post covers paging, cleanup, helper functions and Array.fromAsync.
Streams are the same idea at a lower level, for data too large or too continuous to hold in memory. Node.js has its own stream classes in node:stream, and the web has ReadableStream, WritableStream and TransformStream, which Node.js 24 also supports. Both can be read with for await, both can be converted into the other and both need backpressure so that a fast producer does not overrun a slow consumer. The posts on streams, the three Web Stream classes and backpressure cover them.
const text = new ReadableStream({
start(controller) {
controller.enqueue("hello ");
controller.enqueue("streams");
controller.close();
},
});
const upper = new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk.toUpperCase());
},
});
let output = "";
for await (const chunk of text.pipeThrough(upper)) output += chunk;
console.log(output);HELLO STREAMSFor events that fire repeatedly, you have three models, and they are worth telling apart: an event emitter pushes values to current listeners, a promise delivers one value, and an observable, from a library such as RxJS, delivers many values lazily with operators for combining them. The comparison is in the post on emitters, promises and observables, and the RxJS vocabulary for promise users is in this post.
Concurrency, parallelism and the limits of one thread
Because the main thread runs one piece of code at a time, asynchronous code overlaps waiting and never overlaps computation. Three 50 ms waits started together finish in about 50 ms. Three 50 ms computations started together take about 150 ms, however you arrange them, because the thread is busy during every one of them. Telling the two apart is the key to choosing a tool, and the post on concurrency versus parallelism works through it.
function busy(ms) {
const end = Date.now() + ms;
while (Date.now() < end) {
// holding the thread
}
}
const start = Date.now();
await Promise.all([
Promise.resolve().then(() => busy(60)),
Promise.resolve().then(() => busy(60)),
]);
console.log("took at least 115 ms:", Date.now() - start >= 115);took at least 115 ms: truePromise.all coordinated the two functions and did not run them in parallel. To compute in parallel you need more threads: Web Workers in the browser and worker_threads in Node.js. Each worker has its own event loop and heap and communicates by messages, which are copied unless you transfer an ArrayBuffer or share memory with a SharedArrayBuffer. Workers cost startup time and memory, so use them for work measured in tens of milliseconds or more, and reuse them in a pool. The posts on Web Workers and shared memory and atomics cover the details.
Concurrency without parallelism is not free of races, either. Every await is a gap in which other code can run, so a read-modify-write that spans an await can lose updates, a check followed by an await and an action can act on stale state, responses can arrive out of order and two clicks can start the same operation twice. The post on race conditions describes five such races and their fixes, and the short version is to keep a check and its action in the same synchronous stretch, tag requests with sequence numbers, share in-flight promises and serialize critical sections.
Scheduling: timers, frames and idle time
Timers are the most used and most misunderstood part of the toolbox. setTimeout(fn, 100) means "no sooner than 100 ms, when the thread is free", so a busy thread makes it late, a background tab may throttle it to once a second and the delay is clamped to at least 1 ms, with a maximum of about 24.8 days. Never count ticks to measure time. Derive elapsed time from performance.now(), which is monotonic, and treat the timer only as a way of waking up. The post on timer precision explains the causes and a drift-free loop.
Different needs call for different schedulers.
| You want to | Use |
|---|---|
| Run right after the current code | queueMicrotask |
| Run after pending I/O in Node.js | setImmediate |
| Wait a real amount of time | setTimeout |
| Update visuals before the next paint | requestAnimationFrame |
| Do background work when idle | requestIdleCallback or scheduler.postTask |
| Let input run during a long job | scheduler.yield() |
The posts on queueMicrotask, setTimeout and setImmediate, nextTick, requestAnimationFrame, idle callbacks and postTask and scheduler.yield cover each. The common thread is yielding: a long task blocks input, and splitting it into slices with a macrotask boundary between them keeps the page responsive. Only a macrotask boundary helps. Awaiting a promise yields to other microtasks, which run before input, so it does not.
Carrying state across asynchronous boundaries
A server handling many requests at once needs per-request data, such as a request id or the current user, available deep in the call tree without passing it through every function. A global variable cannot hold it, because two requests overlapping through an await would overwrite each other's values. AsyncLocalStorage from node:async_hooks solves this by attaching a value to a logical flow of execution, and it follows promises, timers and callbacks started within it.
import { AsyncLocalStorage } from "node:async_hooks";
const context = new AsyncLocalStorage();
function log(message) {
console.log(`[${context.getStore().requestId}] ${message}`);
}
async function handle(requestId, delay) {
await context.run({ requestId }, async () => {
await new Promise((resolve) => setTimeout(resolve, delay));
log("done");
});
}
await Promise.all([handle("req-1", 20), handle("req-2", 5)]);[req-2] done
[req-1] doneEach line carries its own request id, though log received none. The async context post covers the pitfalls, mainly callbacks that run later from a shared queue and must be bound with AsyncResource.bind. A proposal called AsyncContext aims to bring the same idea to the language itself.
Patterns you will write again and again
A few small utilities appear in nearly every asynchronous code base. Write them once, test them and reuse them.
A timeout. The modern form needs only a signal.
async function withTimeout(operation, ms) {
return operation(AbortSignal.timeout(ms));
}
const slow = (signal) =>
new Promise((resolve, reject) => {
const timer = setTimeout(() => resolve("finished"), 100);
signal.addEventListener("abort", () => {
clearTimeout(timer);
reject(signal.reason);
});
});
try {
await withTimeout(slow, 10);
} catch (error) {
console.log(error.name);
}TimeoutErrorRetry with backoff. Retry operations that are safe to repeat, wait longer after each failure and give up after a limit.
async function retry(operation, { attempts = 3, baseMs = 10 } = {}) {
let lastError;
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
return await operation(attempt);
} catch (error) {
lastError = error;
if (attempt < attempts) {
await new Promise((resolve) => setTimeout(resolve, baseMs * 2 ** (attempt - 1)));
}
}
}
throw new Error(`failed after ${attempts} attempts`, { cause: lastError });
}
const result = await retry(async (attempt) => {
if (attempt < 3) throw new Error(`attempt ${attempt} failed`);
return `succeeded on attempt ${attempt}`;
});
console.log(result);succeeded on attempt 3Add random jitter to the delay in production, so many clients retrying together do not hit a recovering service in lockstep, and never retry an operation that is not idempotent without an idempotency key.
A concurrency limit. Promise.all starts everything at once. A small pool runs a fixed number at a time.
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], index);
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, lane));
return results;
}
let running = 0;
let peak = 0;
const doubled = 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 * 2;
});
console.log(doubled);
console.log("peak concurrency:", peak);[ 2, 4, 6, 8, 10, 12 ]
peak concurrency: 2Each lane takes the next unclaimed item, so the work stays balanced when items take different times, and the results come back in input order. Choose the limit from what the receiving service can take, and measure before raising it.
Deduplicating in-flight work. Store the promise, not the value, so concurrent callers share one load.
const inFlight = new Map();
function loadOnce(key, loader) {
if (!inFlight.has(key)) {
inFlight.set(
key,
loader().finally(() => inFlight.delete(key)),
);
}
return inFlight.get(key);
}
let loads = 0;
const loader = async () => {
loads += 1;
await new Promise((resolve) => setTimeout(resolve, 5));
return "data";
};
await Promise.all([loadOnce("a", loader), loadOnce("a", loader), loadOnce("a", loader)]);
console.log("loads:", loads);loads: 1Serializing a critical section. A tiny promise-based mutex makes a read-modify-write exclusive.
class Mutex {
#tail = Promise.resolve();
run(task) {
const result = this.#tail.then(task);
this.#tail = result.catch(() => {});
return result;
}
}
const mutex = new Mutex();
let balance = 100;
const withdraw = (amount) =>
mutex.run(async () => {
const current = balance;
await new Promise((resolve) => setTimeout(resolve, 5));
balance = current - amount;
});
await Promise.all([withdraw(30), withdraw(50)]);
console.log("balance:", balance);balance: 20Keep the protected section short, because it serializes everything inside it.
Testing asynchronous code
Asynchronous tests fail in two characteristic ways: they pass without checking anything, and they fail sometimes. The first happens when a test forgets to return or await a promise, so the runner finishes before the assertions run. Always make the test function async and await the work, and use assert.rejects or the equivalent for expected failures.
import test from "node:test";
import assert from "node:assert/strict";
test("a failing call rejects with the right message", async () => {
const failing = async () => {
throw new Error("nope");
};
await assert.rejects(failing(), { message: "nope" });
});ā a failing call rejects with the right messageThe second happens when a test depends on real time. A test that waits 100 ms and asserts that something happened is a flaky test, because a loaded machine will sometimes need 150. Prefer to wait on something you control, such as a deferred promise or an event, and use fake timers, which test runners provide, to advance time by hand. The built-in runner has mock.timers for this. Test the lower bound and the order of events, such as "the slow path produced a timeout error", and not exact durations.
Also test the unhappy paths as carefully as the happy one. Write a case where the operation fails, one where it is slow and one where it never answers, and assert what the caller sees. After the test finishes, no timers should remain pending and no promise should be left unsettled, and a test run that hangs at the end almost always points to a timer or socket that was never cleared.
Debugging asynchronous code
Three habits find most asynchronous bugs. First, log the order, not the values. Put a label with a counter at each scheduling point and each callback, and read the sequence the lines appear in. Nearly every ordering bug is a callback that was assumed to run earlier or later than it does. Second, read the stack trace with its limits in mind. After an await, the engine rebuilds the callers from the chain of awaiting async functions, and the chain breaks at timers, event emitters and promise plumbing that does not use await. Keep important paths in async and await, name your functions and wrap errors with a cause. Third, make the failure louder. Run Node.js with --unhandled-rejections=strict while testing so that a dropped promise fails at once, enable a linter rule for floating promises, and give every long operation a deadline so a hang becomes a timeout with a name.
Browser developer tools help in particular ways. The Performance panel shows each task as a block on the main thread, so a long block explains a frozen page and a gap explains an idle one. The async stack option in the debugger stitches the frames together across await, and breakpoints inside a then callback stop with the promise chain visible. In Node.js, monitorEventLoopDelay from node:perf_hooks measures how late the loop is running, which is the number to alert on in production, since a loop that is late is a loop that is blocked.
Mistakes that appear in nearly every code base
**A missing
await.** The variable holds a promise, and property reads on it returnundefined. A linter rule for floating promises catches this.**
forEachwith anasynccallback.** The loop ignores the promises. Usefor...oforPromise.allwithmap.**A bare
return promiseinsidetry.** Thecatchnever sees the rejection. Usereturn await.Swallowed errors. A
catchthat logs and returns nothing turns a failure into a silent success.Unbounded fan-out. A promise per item for a list of thousands overwhelms whatever it calls. Limit the concurrency.
Timers as clocks. Counting ticks drifts. Compare against
performance.now().A promise where an event is needed. A promise settles once, so it cannot represent something that repeats.
**Doing computation inside
async.**asyncdoes not move work off the thread. Use a worker, or slice the work.Mixing synchronous and asynchronous behavior. A function that calls its callback immediately in one branch and later in another is unpredictable. Always be one or the other.
A thenable by accident. An object with a method named
thenis treated as a promise byawait, and the code hangs. Avoid the name on ordinary objects (thenables).
Choosing the right tool
Start from what you are modeling. If it is one result, use a promise and async/await. If it is a sequence over time with a consumer that sets the pace, use an async generator or a stream. If it is a set of notifications with many listeners, use an event emitter. If it needs time-based composition, such as debouncing, retries and cancellation of stale work, consider observables. If the work is computation, use a worker. If it must be cancelled, thread an AbortSignal through it from the start.
Then ask the overlap question for every group of operations: must they run in order, may they run together, may only the latest matter, or must duplicates be blocked? For plain promises, the answers map onto a sequential loop, Promise.all or a limited pool, a sequence number or an abort of the stale request, and an in-flight guard. In RxJS the same answers are concatMap, mergeMap, switchMap and exhaustMap.
Last, decide how failure behaves before writing the happy path: what is retried, what has a deadline, what is shown to the user, what is logged and what stops the process. Asynchronous code that works on a good day is the easy part. The difference between a program that survives production and one that does not is usually what it does when the network is slow, the service is down or the user clicks twice.
Where to go next
This guide is the map, and the individual posts are the territory. For the runtime itself, read the event loop guide. For promises and async/await in depth, read the promises guide and the async/await guide. For stopping work cleanly, read the cancellation guide. For the first steps, what asynchronous programming is and synchronous versus asynchronous code are the gentlest starting points.


