Sub topic 14
Combinators Don't Cancel: Using AbortController
Every combinator in this tutorial stops waiting at some point. Promise.all stops at the first rejection. Promise.race stops at the first settlement. Promise.any stops at the first fulfillment. None of them stops the work. The timers keep ticking, the HTTP requests keep downloading, and the database queries keep running. This chapter shows why that happens and how to use AbortController to stop the work you no longer need.
This chapter assumes you can write async functions with await and try/catch/finally, and that you have read the earlier chapters on fail-fast rejection in Promise.all, the timeout pattern with Promise.race, and Promise.any. The examples use top-level await, so run them as ES modules (.mjs files) in Node 18 or later, or in a modern browser console.
Why a Promise Cannot Cancel Its Operation
A promise is a placeholder for a result. It is not a handle to the operation that produces that result. When you call fetch(url), the request starts right away, and the promise you get back only reports how it ends. A combinator receives these placeholders. It can subscribe to them with .then, but it has no way to reach back into the operation and stop it.
This small demo shows the losing task finishing its work after the race has been decided:
const task = (name, ms) =>
new Promise((resolve) => {
setTimeout(() => {
console.log(`${name} finished its work`);
resolve(name);
}, ms);
});
const winner = await Promise.race([task('fast', 100), task('slow', 500)]);
console.log('winner:', winner);
// fast finished its work
// winner: fast
// slow finished its work <- about 400 ms laterIf slow were a real request, it would still use a socket, bandwidth, and server time, and its result would be thrown away. With Promise.all, a fail-fast rejection leaves every other request running. With a Promise.race timeout, the "timed out" operation keeps going in the background.
AbortController in Brief
AbortController is built into browsers and Node. It has two parts:
| Part | Role |
|---|---|
| `controller.signal` | An `AbortSignal` you pass to operations. It exposes `aborted`, `reason`, `throwIfAborted()`, and an `abort` event. |
| `controller.abort(reason?)` | Marks the signal as aborted, sets `signal.reason`, and fires the `abort` event once. |
If you call abort() with no argument, signal.reason becomes a DOMException whose name is 'AbortError'. A controller works only once. After you abort it, it stays aborted, so create a new controller for each batch of work.
Many APIs accept a signal: fetch, Node's fs.promises.readFile, timers/promises setTimeout, addEventListener, and stream APIs. When the signal aborts, these APIs stop their work and reject their promise with signal.reason.
Pattern: Cancel the Losers After Promise.any
The standard pattern has three steps. Create one controller, give its signal to every operation, and abort in a finally block once the combinator has settled:
async function fetchFastest(urls) {
const controller = new AbortController();
try {
return await Promise.any(
urls.map((url) =>
fetch(url, { signal: controller.signal }).then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status} from ${url}`);
return res;
})
)
);
} finally {
controller.abort();
}
}The finally block runs whether Promise.any fulfills or rejects with an AggregateError. Aborting after the winner arrives is safe. A fetch whose headers have already arrived is not undone. fetch resolves its promise once the response headers arrive, and the body is still read through the same signal. So in this function, aborting in finally would also cut off the winner's body. When you need the body, read it inside the mapped function before returning:
async function fetchFastestJson(urls) {
const controller = new AbortController();
try {
return await Promise.any(
urls.map(async (url) => {
const res = await fetch(url, { signal: controller.signal });
if (!res.ok) throw new Error(`HTTP ${res.status} from ${url}`);
return res.json(); // body fully read before this promise fulfills
})
);
} finally {
controller.abort();
}
}The losers' AbortError rejections do not cause "unhandled rejection" warnings. Each combinator attaches handlers to every input, so those late rejections count as handled even though nothing uses them.
Pattern: Stop the Siblings When Promise.all Fails Fast
With Promise.all, the first rejection is the moment to stop the others. Abort in catch, then rethrow:
async function fetchAllOrNothing(urls) {
const controller = new AbortController();
try {
return await Promise.all(
urls.map(async (url) => {
const res = await fetch(url, { signal: controller.signal });
if (!res.ok) throw new Error(`HTTP ${res.status} from ${url}`);
return res.json();
})
);
} catch (err) {
controller.abort(err); // pass the cause along as signal.reason
throw err;
}
}Do not abort in finally here. On success every request has finished anyway, and the catch path makes the intent clear. Passing err to abort means any code that inspects signal.reason can see why the batch was cancelled.
Making Your Own Operations Abortable
A signal only helps if the operation listens to it. When you write your own promise-returning function, accept a signal and handle three cases: the signal is already aborted, it aborts while the work runs, and the work finishes normally (in which case you remove the listener).
function abortableDelay(ms, value, signal) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
const timer = setTimeout(() => {
signal?.removeEventListener('abort', onAbort);
resolve(value);
}, ms);
function onAbort() {
clearTimeout(timer);
reject(signal.reason);
}
signal?.addEventListener('abort', onAbort, { once: true });
});
}
const controller = new AbortController();
try {
const winner = await Promise.race([
abortableDelay(100, 'fast', controller.signal),
abortableDelay(500, 'slow', controller.signal),
]);
console.log('winner:', winner); // winner: fast
} finally {
controller.abort(); // the 'slow' timer is cleared, not left running
}For multi-step async functions, call signal.throwIfAborted() between steps so that a cancelled job does not start its next expensive step.
Timeouts That Actually Stop the Work
The Promise.race timeout from the earlier chapter rejects on time, but the slow operation keeps running. A signal-based timeout stops it. AbortSignal.timeout(ms) returns a signal that aborts after ms milliseconds with a DOMException named 'TimeoutError'. AbortSignal.any(signals) combines several signals into one that aborts when any of them does. It is available in Node 20.3+ and current browsers.
async function getJson(url, { signal, timeoutMs = 5000 } = {}) {
const signals = [AbortSignal.timeout(timeoutMs)];
if (signal) signals.push(signal);
try {
const res = await fetch(url, { signal: AbortSignal.any(signals) });
if (!res.ok) throw new Error(`HTTP ${res.status} from ${url}`);
return await res.json();
} catch (err) {
if (err.name === 'TimeoutError') {
throw new Error(`Timed out after ${timeoutMs} ms: ${url}`, { cause: err });
}
throw err; // includes 'AbortError' from the caller's signal
}
}This function supports both a per-request deadline and cancellation by the caller. You can combine it with any combinator by passing the batch controller's signal to every getJson call.
Common Mistakes
- Creating a controller per request but aborting none of them. If the combinator cannot see the controllers, nothing gets cancelled. Share one controller per batch, or keep the controllers in an array.
- Reusing an aborted controller. Once aborted, every later operation given that signal fails immediately. Create a fresh controller per batch.
- Treating
AbortErroras a real failure. Logging or retrying aborted requests creates noise. Checkerr.name === 'AbortError'and skip reporting those errors. - Leaking listeners. Long-lived signals collect
abortlisteners from every operation that does not remove its listener. Use{ once: true }and remove the listener when the work completes. - Expecting abort to undo side effects. Aborting a
POSTstops the client from waiting for the response. The server may already have processed the request. Cancellation saves resources, and it does not roll back work that was already done.
Exercise
In the first demo, Promise.race([task('fast', 100), task('slow', 500)]) still logs "slow finished its work". If you changed task to accept a signal and passed controller.signal to both, but never called controller.abort(), would the slow timer stop? Why or why not?
Show answer
No. Passing a signal does nothing by itself. The timer is only cleared when the signal's abort event fires, which happens when you call controller.abort(), typically in a finally block after the race settles.
Exercise
In fetchFastest, controller.abort() runs in finally right after Promise.any fulfills with a Response. A caller then runs await (await fetchFastest(urls)).json() and gets an AbortError. Explain the cause and the fix.
Show answer
fetch fulfills when the headers arrive, and the body is still streamed under the same signal. Aborting in finally cancels the winner's unread body as well. Read the body (for example return res.json()) inside the mapped function so the value is complete before Promise.any fulfills and the abort happens, as fetchFastestJson does.
Exercise
Why is the AbortSignal.timeout version of a timeout usually better for fetch than the Promise.race version, and when would you still need Promise.race?
Show answer
The signal version actually cancels the request, which frees the connection and stops the download. The race version only stops waiting. You still need Promise.race, or must write a wrapper, for operations that do not accept a signal, because there is nothing for the signal to stop.