Sub topic 13
Cancelling Work with AbortController
This chapter assumes you are comfortable with async functions, await, and handling rejections with try/catch/finally, all covered in earlier chapters. You also need Node.js 18 or later, or a modern browser, because both include fetch and AbortController.
Why cancellation matters
A Promise has no built-in cancel button. Once you start a fetch, it keeps running even if the user leaves the page, types a new search term, or stops caring about the result. Waiting for an operation you no longer need wastes bandwidth. It can also cause bugs: a slow, stale response can arrive after a newer one and overwrite it.
The standard fix is AbortController. This object lets one piece of code signal "stop" to any operation that agrees to listen.
The working model
An AbortController has two parts:
| Part | Type | Who uses it |
|---|---|---|
| `controller.signal` | `AbortSignal` | Passed to the operation, which listens for the abort |
| `controller.abort(reason)` | Method | Called by the code that wants to cancel |
Calling abort() does three things. It sets signal.aborted to true, stores the reason in signal.reason, and fires an abort event on the signal. An operation that receives the signal, such as fetch, reacts by rejecting its Promise. If you call abort() with no argument, the Promise rejects with a DOMException whose name is 'AbortError'.
A timeout for fetch
The most common use is a time limit. Start a timer that calls abort(), and clear the timer when the request finishes either way:
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);
}
}The finally block matters. Without it, a fast request would leave a timer running that later aborts a controller nobody cares about. The signal also covers response.json(): if the abort happens while the body is still downloading, that await rejects too.
Making your own functions cancellable
AbortSignal only works when the operation listens to it. Your own async helpers can listen too. This delay rejects early when the signal aborts and cleans up after itself:
function delay(ms, { signal } = {}) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
const timer = setTimeout(() => {
signal?.removeEventListener('abort', onAbort);
resolve();
}, ms);
function onAbort() {
clearTimeout(timer);
reject(signal.reason);
}
signal?.addEventListener('abort', onAbort, { once: true });
});
}
async function main() {
const controller = new AbortController();
setTimeout(() => controller.abort(), 100);
try {
await delay(1000, { signal: controller.signal });
console.log('finished');
} catch (err) {
console.log('cancelled:', err.name); // cancelled: AbortError
}
}
main();Inside longer async functions, call signal.throwIfAborted() between steps to stop at a safe point.
Common errors
- Reusing a controller. A signal aborts once and stays aborted. Create a new controller for each new request.
- Treating cancellation as a failure. An abort is usually intentional. Check
err.nameand skip error messages or retries forAbortError. - Expecting a cancelled request to undo work. Aborting stops your code from waiting. A server may already have processed a POST request.
- Forgetting cleanup. Clear timers and remove listeners in
finally, or they keep running after the work is done.
Exercise
A search box calls search(term) on every keystroke, and slow responses for old terms sometimes overwrite newer results. Using AbortController, how would you make sure only the latest request can update the page?
Show answer
Keep the current controller in a variable outside the function. At the start of each search call, call abort() on the previous controller if there is one, then create a new controller and pass its signal to fetch. In the catch block, ignore errors whose name is 'AbortError' and handle only real failures. Older requests now reject instead of resolving, so they never reach the code that updates the page.
Exercise
You call controller.abort() and then later pass controller.signal to a new fetch. What happens?
Show answer
The fetch rejects right away with the signal's stored reason (an AbortError), because the signal is already aborted. A signal cannot be reset, so each new operation needs a new AbortController.