Sub topic 12
Handling Cancellation in the Caller
So far you have built functions that reject when their signal aborts. This chapter looks at the code on the other side of the call, the code that creates the controller, awaits the result, and has to decide what a rejection means. It assumes you already know promises, async/await, try/catch, and the abort reasons covered in the previous chapter: the default AbortError, the TimeoutError produced by timeout signals, and custom values passed to abort().
A caller sees three kinds of rejection, and each needs a different response:
| Outcome | Typical `err` | What the caller should do |
|---|---|---|
| The caller cancelled | `signal.reason` (an `AbortError` by default, or a custom reason) | Stop quietly. Show no error message and do no retry. |
| A deadline passed | `DOMException` named `TimeoutError` | Tell the user it was slow, and maybe offer a retry |
| Real failure | `TypeError`, `Error`, HTTP errors | Report it, log it, retry if that makes sense |
If you treat these three the same way, users get "Something went wrong" banners every time they click Cancel or type the next letter in a search box.
Why `err.name === 'AbortError'` Is Not Enough
The usual first attempt checks the error name:
try {
await doWork({ signal: controller.signal });
} catch (err) {
if (err.name === 'AbortError') return; // ignore cancellation
throw err;
}This works only while everyone calls abort() with no argument. When you call controller.abort(new Error('User navigated away')), well-behaved functions reject with that exact Error, and its name is "Error". The check misses it and the cancellation gets reported as a failure.
There is also a false positive. An AbortError can come from a signal you didn't create, such as one aborted inside a library. The name tells you some signal aborted. It does not tell you that your signal did.
The caller owns the signal, so the caller can ask the signal directly. If signal.aborted is true and the error is signal.reason, this caller cancelled the work.
A Classification Helper
Put that logic in one place:
function classifyError(err, signal) {
if (signal?.aborted && (err === signal.reason || err?.name === 'AbortError')) {
return 'cancelled';
}
if (err?.name === 'TimeoutError') {
return 'timeout';
}
return 'failure';
}The err?.name === 'AbortError' fallback handles older runtimes and third-party code that reject with a fresh AbortError instead of forwarding signal.reason. The signal.aborted guard comes first, so a stray AbortError from someone else's signal does not count as your cancellation.
Timeouts get their own branch. A function that adds a deadline internally can time out while the caller's own signal is still not aborted. The caller didn't ask for that outcome, so it should not be silenced.
A Complete Caller: The Search Box
A search-as-you-type box is the classic case. Each keystroke starts a request, and starting a new one should cancel the previous one. The script below runs in Node 18+ or a browser console. It uses the cancellable delay() from earlier chapters to simulate a slow server.
function delay(ms, { signal } = {}) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
const onAbort = () => {
clearTimeout(timerId);
reject(signal.reason);
};
const timerId = setTimeout(() => {
signal?.removeEventListener('abort', onAbort);
resolve();
}, ms);
signal?.addEventListener('abort', onAbort, { once: true });
});
}
async function searchApi(query, { signal } = {}) {
await delay(300, { signal });
if (query === 'boom') throw new Error('Server error');
return [`${query} result 1`, `${query} result 2`];
}
function classifyError(err, signal) {
if (signal?.aborted && (err === signal.reason || err?.name === 'AbortError')) {
return 'cancelled';
}
if (err?.name === 'TimeoutError') return 'timeout';
return 'failure';
}
let current = null;
async function onSearchInput(query) {
current?.abort(new Error('Superseded by a newer search'));
const controller = new AbortController();
current = controller;
console.log(`[${query}] spinner on`);
try {
const results = await searchApi(query, { signal: controller.signal });
console.log(`[${query}] render:`, results);
} catch (err) {
const kind = classifyError(err, controller.signal);
if (kind === 'cancelled') {
console.log(`[${query}] cancelled: ${err.message}`);
return;
}
if (kind === 'timeout') {
console.log(`[${query}] too slow, please retry`);
return;
}
console.log(`[${query}] error: ${err.message}`);
} finally {
if (current === controller) {
current = null;
console.log(`[${query}] spinner off`);
}
}
}
onSearchInput('ja');
setTimeout(() => onSearchInput('jav'), 100);
setTimeout(() => onSearchInput('java'), 200);
setTimeout(() => onSearchInput('boom'), 1000);Only java renders. The ja and jav searches print cancelled: Superseded by a newer search, and boom prints a real error. The custom reason gets through because classifyError compares the error with signal.reason and ignores its name.
The finally block deserves attention:
finallyruns in all three cases, so cleanup such as hiding a spinner belongs there and not incatch.- The
current === controllerguard stops a cancelled request from hiding the spinner that the newer request just turned on. Without the guard, thejacancellation would switch the spinner off whilejavais still loading.
Gotchas on the Caller Side
Aborting does not undo a result you already have
Calling abort() after the promise has settled does nothing to it. Some callee functions also ignore the signal, or check it too late, and resolve anyway. If a stale result would be harmful, check again after the await:
async function loadProfile(id, signal, fetchProfile, render) {
const profile = await fetchProfile(id, { signal });
if (signal.aborted) return; // the callee resolved anyway; drop the stale data
render(profile);
}This check costs one line and protects you from callees that don't handle cancellation properly.
Middle layers must rethrow, not swallow
Only the code that created the controller should silence cancellation. A helper in the middle of the stack that catches an AbortError and returns null or [] breaks every caller above it, because they can no longer tell "no data" from "cancelled". In intermediate layers, rethrow:
async function loadDashboard({ signal } = {}, loadWidgets) {
try {
return await loadWidgets({ signal });
} catch (err) {
if (signal?.aborted) throw err; // pass cancellation up untouched
throw new Error('Dashboard failed to load', { cause: err });
}
}Wrapping real failures with cause is fine. Wrapping a cancellation is not, because the new Error is no longer signal.reason and the top-level check fails. If you must wrap it, make the top-level classifier also look at err.cause.
Unhandled rejections after abort
When you abort work that nobody is awaiting, as in fire-and-forget calls, the rejection is still unhandled. Node prints a warning and, by default, exits the process. Browsers log an "Uncaught (in promise)" error. Attach a handler to every cancellable promise you start, even if the handler only filters out cancellation:
function fireAndForget(promise, signal) {
promise.catch((err) => {
if (classifyError(err, signal) !== 'cancelled') console.error(err);
});
}Don't retry cancellations
Retry loops must check classification before retrying. If they don't, a retry wrapper will start the work again right after the user cancelled it. The signal is already aborted, so each new attempt rejects at once. That costs little, but the loop logs pointless errors or spins until its retry limit runs out.
async function withRetry(task, { signal, attempts = 3 } = {}) {
for (let i = 1; ; i++) {
try {
return await task({ signal });
} catch (err) {
if (signal?.aborted || i >= attempts) throw err;
}
}
}Summary of the Caller Pattern
- Create the controller where the decision to cancel is made, and keep a reference to it.
- In
catch, classify with the signal itself:signal.abortedpluserr === signal.reason. Use the name check only as a fallback. - Give timeouts their own branch, separate from user cancellation.
- Put cleanup in
finally, guarded so an old request cannot undo a new request's state. - Rethrow cancellation untouched in middle layers. Swallow it only at the top.
Exercise
A caller runs controller.abort(new Error('Tab closed')) and its catch block checks if (err.name === 'AbortError') return;. The cancellable function forwards signal.reason correctly. What happens, and how should the check change?
Show answer
The function rejects with the custom Error, whose name is "Error", so the check fails and the cancellation is reported as a failure. Check the signal instead: if (controller.signal.aborted && err === controller.signal.reason) return;. You can add || err.name === 'AbortError' inside the aborted guard as a fallback for older code.
Exercise
In the search box example, what goes wrong if the current === controller guard is removed from the finally block?
Show answer
When a newer search aborts an older one, the older request's finally still runs. It sets current to null and hides the spinner while the newer request is still loading. It also clears the reference, so the next keystroke can't abort the in-flight request.
Exercise
A helper catches every error from fetchItems({ signal }) and returns an empty array. Why is this a problem for cancellation, and what should it do instead?
Show answer
Callers can no longer tell "cancelled" from "no items", so they may render an empty list for a request the user abandoned. The helper should rethrow when signal?.aborted is true and only convert or wrap real failures.