Sub topic 13
Cancelling Work with AbortController
Earlier chapters showed how to start asynchronous work, wait for it with await, and handle failures with try/catch/finally. One gap remains. Once a Promise exists, nothing in the Promise API lets you stop the work behind it. A slow request keeps running after the user has left the page. A search request for "ja" can still be in flight when the user has already typed "javascript". This chapter covers AbortController, the standard way to cancel pending asynchronous operations in browsers and in Node.js.
This chapter assumes you are comfortable with:
asyncfunctions andawaittry/catch/finallyin async code, including rethrowing errorsPromise.raceandPromise.all- Creating a Promise with
new Promise((resolve, reject) => ...) - Running code in Node.js 20 or later, or in a current browser
The Working Model: Controller, Signal, Listener
Cancellation is split between two objects:
- The AbortController belongs to the code that decides whether to cancel. It has one method,
abort(). - The AbortSignal (
controller.signal) belongs to the code doing the work. That code readssignal.aborted, readssignal.reason, and listens for theabortevent.
The split keeps the two roles apart. A function that receives a signal can react to cancellation but cannot trigger it. Only the holder of the controller can.
Here is the smallest working example. It needs no network access because it only inspects the signal.
const controller = new AbortController();
const { signal } = controller;
signal.addEventListener('abort', () => {
console.log('abort event fired');
});
console.log(signal.aborted); // false
controller.abort();
console.log(signal.aborted); // true
console.log(signal.reason.name); // 'AbortError'
controller.abort(); // no effect: a signal aborts only onceCalling abort() more than once does nothing after the first call. A controller is also single-use. Once aborted, its signal stays aborted for good, so each new operation that should be cancellable on its own needs a new controller.
Cancelling fetch
fetch accepts a signal option. If the signal aborts before the response finishes, the Promise returned by fetch rejects. Because the rejection happens at the await, your existing try/catch handles it like any other error.
async function fetchWithTimeout(url, ms) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
const response = await fetch(url, { signal: controller.signal });
return await response.json();
} catch (err) {
if (err.name === 'AbortError') {
throw new Error(`Request timed out after ${ms} ms`);
}
throw err;
} finally {
clearTimeout(timer);
}
}
fetchWithTimeout('https://api.github.com/zen', 5)
.then(data => console.log(data))
.catch(err => console.log(err.message)); // likely: Request timed out after 5 msThree details in this function are easy to get wrong:
- The
finallyclears the timer. If the request succeeds quickly and you skipclearTimeout, the timer still fires later and aborts a controller nobody uses. In Node.js a pending timer can also keep the process alive longer than needed. - The signal also covers the body. Cancellation applies to reading the response, too. If the signal aborts while
response.json()is still reading data, that Promise rejects as well. This is whyawait response.json()sits inside the sametry. - Check
err.name, notinstanceof Erroralone. The default abort reason is aDOMExceptionnamed'AbortError'. Network failures reject with aTypeErrorinstead. Checking the name tells cancellation apart from real failures.
Built-in Helpers: AbortSignal.timeout and AbortSignal.any
The timeout pattern above is so common that the platform provides a shortcut. AbortSignal.timeout(ms) returns a signal that aborts by itself after ms milliseconds. Its reason is a DOMException named 'TimeoutError', which lets you tell a timeout apart from a user's cancel.
AbortSignal.any([...signals]) returns a signal that aborts as soon as any input signal aborts, and it takes that signal's reason. Combining the two gives you "cancel when the user clicks Stop or after 3 seconds" without any timer bookkeeping.
async function load(url, userSignal) {
const signal = AbortSignal.any([userSignal, AbortSignal.timeout(3000)]);
try {
const response = await fetch(url, { signal });
return await response.text();
} catch (err) {
if (err.name === 'TimeoutError') return 'timed out';
if (err.name === 'AbortError') return 'cancelled by user';
throw err;
}
}
const stop = new AbortController();
load('https://api.github.com/zen', stop.signal).then(console.log);
stop.abort(); // prints: cancelled by user| Tool | Aborts when | Default reason name | Availability |
|---|---|---|---|
| `new AbortController()` + `abort()` | You call `abort()` | `AbortError` | All current runtimes |
| `AbortSignal.timeout(ms)` | `ms` milliseconds pass | `TimeoutError` | Node 17.3+, current browsers |
| `AbortSignal.any(signals)` | Any input signal aborts | Copied from that signal | Node 20.3+, current browsers |
| `AbortSignal.abort(reason)` | Immediately (already aborted) | `AbortError` | Node 15.12+, current browsers |
Making Your Own Functions Cancellable
fetch supports signals because its authors wrote it to. Your functions only support cancellation if you write them to. The convention is simple: accept a signal in an options object, and reject with signal.reason when it aborts.
A cancellable delay shows every part of the pattern:
function delay(ms, { signal } = {}) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
const onAbort = () => {
clearTimeout(timer);
reject(signal.reason);
};
const timer = setTimeout(() => {
signal?.removeEventListener('abort', onAbort);
resolve();
}, ms);
signal?.addEventListener('abort', onAbort, { once: true });
});
}
async function main() {
const controller = new AbortController();
setTimeout(() => controller.abort(), 200);
try {
await delay(1000, { signal: controller.signal });
console.log('finished');
} catch (err) {
console.log('stopped:', err.name); // stopped: AbortError
}
}
main();Each part has a job:
- The early check. An
abortevent fires only once, at the moment of aborting. If the signal was already aborted before the call, no event will ever arrive, so you must checksignal.abortedfirst. - Undoing the work.
clearTimeoutactually stops the timer. Rejecting the Promise alone would only stop the caller from waiting. The timer would still fire. - Removing the listener. When the work finishes normally, remove the listener. A long-lived signal shared by many operations would otherwise collect listeners, and that leaks memory.
- Rejecting with
signal.reason. This keeps the error type consistent withfetch, so callers can handle both the same way.
Cancelling loops and multi-step work
For code that runs in steps, such as a loop over pages or a chain of awaits, call signal.throwIfAborted() between steps. It throws signal.reason if the signal has aborted and does nothing otherwise. Pass the same signal down to every inner call so one abort() stops the whole tree.
async function processAll(items, { signal }) {
const results = [];
for (const item of items) {
signal.throwIfAborted();
await delay(100, { signal }); // stands in for real async work
results.push(item * 2);
}
return results;
}This works only if the delay function from the previous example is defined in the same file.
Gotchas and Failure Modes
Aborting does not interrupt running code
JavaScript runs one piece of synchronous code at a time, as the event loop chapter explained. abort() sets a flag and fires an event. It cannot break into a CPU-heavy loop that never yields. If a function runs a 5-second synchronous calculation, aborting has no effect until that calculation returns. Cancellation is cooperative: the work must check the signal at points where it pauses.
Promise.race picks a winner but does not stop the losers
Promise.race([fetch(a), timeout]) lets your code move on when the timeout wins, but the fetch keeps downloading in the background. To actually stop the losing operations, give them a signal and abort it after the race settles:
async function fastest(urls) {
const controller = new AbortController();
try {
return await Promise.any(
urls.map(url =>
fetch(url, { signal: controller.signal }).then(r => r.text())
)
);
} finally {
controller.abort(); // stop the requests that did not win
}
}Aborting after the winner has settled is safe. Aborting an operation that has already finished has no effect.
Stale responses in search-as-you-type
A common bug: the user types quickly, several requests are in flight at once, and an older response arrives last and overwrites newer results. The fix is to keep one controller per "latest request" and abort the previous one before starting the next.
let current = null;
async function search(query) {
current?.abort();
current = new AbortController();
const { signal } = current;
try {
const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal });
return await response.json();
} catch (err) {
if (err.name === 'AbortError') return null; // superseded, not a failure
throw err;
}
}Swallowing aborts by accident
A broad catch that logs and returns a fallback value turns cancellation into success. The caller then carries on as though the work had finished. When cancellation reaches code that cannot handle it in a useful way, rethrow it. Only catch it at the level that started the operation and knows that cancelling was intended.
Unhandled rejections from fire-and-forget work
If you abort an operation whose Promise nobody awaits, the rejection is unhandled. Node.js treats unhandled rejections as fatal by default. Attach a .catch to every Promise you start, even ones you plan to abandon.
Decision Guide
| Situation | Use |
|---|---|
| Fixed time limit on one request | `AbortSignal.timeout(ms)` |
| User can cancel, plus a time limit | `AbortSignal.any([userSignal, AbortSignal.timeout(ms)])` |
| Newer request replaces older one | Abort the previous controller before each call |
| Stop the losers after `Promise.any` or `race` | Shared controller, `abort()` in `finally` |
| Your own async function or loop | Accept `{ signal }`, check `aborted`, listen for `abort`, call `throwIfAborted()` between steps |
| CPU-bound synchronous work | Split it into chunks that yield, or move it to a Worker |
Exercise
A function calls controller.abort('user left') and the pending fetch is wrapped in try/catch with if (err.name === 'AbortError') return null;. The catch block does not return null. Instead the string 'user left' reaches the caller as an error. Why, and what are two ways to fix it?
Show answer
When abort() receives a reason, fetch rejects with that exact reason, here the string 'user left'. A string has no name property, so the AbortError check fails and the code falls through to rethrow. Fix it by calling abort() with no argument so the reason is a DOMException named 'AbortError', or by checking if (controller.signal.aborted && err === controller.signal.reason) instead of the error name.
Exercise
Write a cancellable delay(ms, { signal }) from memory. Then explain what goes wrong if you remove the initial if (signal?.aborted) check and call delay(1000, { signal: AbortSignal.abort() }).
Show answer
Without the initial check, the function adds an 'abort' listener to a signal that has already aborted. The abort event fired before the listener existed and will not fire again. The timer runs for the full second and the Promise resolves, so the cancellation is silently ignored. The check if (signal?.aborted) { reject(signal.reason); return; } handles signals that were aborted before the call.
Exercise
const text = await Promise.race([fetch(url).then(r => r.text()), delay(2000).then(() => { throw new Error('timeout'); })]); throws 'timeout' after 2 seconds. Is the network request still running? Rewrite the line so the request actually stops.
Show answer
Yes. Promise.race only decides which result your code sees. The fetch keeps going in the background. Rewrite it as const response = await fetch(url, { signal: AbortSignal.timeout(2000) }); const text = await response.text();. The signal aborts the request itself, and the awaited Promise rejects with a TimeoutError.