Sub topic 14
Combinators Don't Cancel: Using AbortController
This chapter assumes you know how Promise.all, Promise.race, and Promise.any settle, and that you have seen the timeout pattern built with Promise.race. You should also be comfortable with async/await and try/finally.
Settling Is Not Stopping
A combinator watches the promises you give it. It does not control the operations behind those promises. When Promise.race settles, or when Promise.all rejects on its first failure, the other operations keep running. Timers still fire, network requests still download, and database queries still run. Their results are simply ignored.
This matters when the leftover work costs something: bandwidth, server load, rate-limit quota, or side effects such as writes.
Seeing the Leftover Work
The helper below simulates a slow task that can be cancelled. It accepts an AbortSignal, which is the read-only object that an AbortController uses to broadcast "stop". Save the file as cancel.mjs so that top-level await works, then run it with node cancel.mjs.
function task(ms, name, signal) {
return new Promise((resolve, reject) => {
if (signal?.aborted) return reject(signal.reason);
const timer = setTimeout(() => {
console.log(`${name} finished`);
resolve(name);
}, ms);
signal?.addEventListener('abort', () => {
clearTimeout(timer);
console.log(`${name} cancelled`);
reject(signal.reason);
}, { once: true });
});
}
// Without cancellation: the loser still runs to completion
console.log('winner:', await Promise.race([task(50, 'fast'), task(300, 'slow')]));
await new Promise((r) => setTimeout(r, 400)); // "slow finished" appears
// With cancellation: abort as soon as the race is decided
const controller = new AbortController();
try {
const winner = await Promise.race([
task(50, 'fast', controller.signal),
task(300, 'slow', controller.signal)
]);
console.log('winner:', winner);
} finally {
controller.abort(); // "slow cancelled"
}Calling abort() in finally covers both outcomes. If a task wins, the losers stop. If something throws, everything still pending stops. Calling abort() after a task has already finished does nothing, so it is safe to call unconditionally.
Cancelling Real Requests
fetch accepts a signal option. Here, Promise.any takes the first successful response from several mirrors and then cancels the rest:
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 cancelled fetches reject with an AbortError. That causes no unhandled-rejection warnings, because Promise.any already attached handlers to them. One caveat is that aborting also cancels the winner's body stream if you have not read it yet. If you need the body, read it inside the .then before returning, for example with return res.json().
Common Mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Assuming `Promise.all` rejection stops the other tasks | Writes or requests still finish | Abort a shared controller in `catch` or `finally` |
| Making the race timeout reject but leaving the request open | The request keeps running after the timeout | Abort the controller when the timeout fires, or pass `AbortSignal.timeout(ms)` |
| Creating one controller per call but never calling `abort()` | Nothing is cancelled | Call `abort()` in `finally` |
| Reusing an aborted controller | New operations reject immediately | Create a new controller for each batch |
Exercise
You run await Promise.all([saveUser(signal), saveAudit(signal)]) with a shared controller's signal, and saveUser rejects. Without any extra code, what happens to saveAudit, and what single change makes it stop?
Show answer
saveAudit keeps running, because Promise.all only stops waiting for it. Wrap the call in try { ... } finally { controller.abort(); } (or call abort() in catch) so the shared signal tells saveAudit to stop. This only works if saveAudit listens to the signal.
Exercise
Why is it safe to call controller.abort() in finally even when every task has already fulfilled?
Show answer
Aborting has no effect on operations that are already done. Their promises are settled and cannot change state, so the call only stops whatever is still pending.