Sub topic 14
Combining User Cancellation and Timeouts with AbortSignal.any()
This chapter assumes you already know how AbortSignal.timeout() creates a deadline signal. It also assumes you know how callers tell AbortError apart from TimeoutError. Here you will combine that deadline with a signal the caller passes in, so your function stops at whichever comes first.
The problem: one `signal` slot, two reasons to stop
fetch accepts exactly one signal. Your function may have two sources of cancellation:
- The caller's signal, which aborts when the user clicks "Cancel" or navigates away.
- Your own deadline, which aborts after a fixed number of milliseconds.
AbortSignal.any(signals) solves this. It takes an iterable of signals and returns a new signal. The new signal aborts as soon as any of the input signals aborts, and it copies that signal's reason.
A fetch helper with both sources
async function fetchJson(url, { signal, timeoutMs = 5000 } = {}) {
const timeoutSignal = AbortSignal.timeout(timeoutMs);
const combined = signal
? AbortSignal.any([signal, timeoutSignal])
: timeoutSignal;
try {
const response = await fetch(url, { signal: combined });
return await response.json();
} catch (err) {
if (err.name === 'TimeoutError') {
throw new Error(`Timed out after ${timeoutMs} ms`, { cause: err });
}
throw err;
}
}
const controller = new AbortController();
fetchJson('https://example.com/data.json', {
signal: controller.signal,
timeoutMs: 2000,
})
.then((data) => console.log(data))
.catch((err) => {
if (err.name === 'AbortError') {
console.log('cancelled by the user');
} else {
console.error(err.message);
}
});
// Simulate the user cancelling quickly
setTimeout(() => controller.abort(), 100);Some details in this code are easy to miss:
- The
signaloption is still optional. When the caller doesn't pass one, the function uses the timeout signal directly. You don't needany()when there is only one source. - The reason passes through unchanged.
fetchrejects with the combined signal'sreason. That reason is theAbortErrorfromcontroller.abort()or theTimeoutErrorfrom the deadline, so the existingerr.namechecks keep working. - Already-aborted inputs count. If the caller's signal was aborted before the call,
combinedis aborted immediately andfetchrejects at once.
Common errors
| Mistake | What goes wrong | Fix |
|---|---|---|
| Passing only `timeoutSignal` to `fetch` | The user's Cancel button does nothing | Pass the combined signal |
| Creating your own `AbortController` and wiring listeners by hand | Leaked listeners, duplicated logic | Use `AbortSignal.any()` |
| Calling `controller.abort()` on the combined signal | `any()` returns a signal with no controller, so there is nothing to call | Abort one of the input signals |
| Catching every abort as "user cancelled" | Timeouts are reported to the user as cancellations | Check `err.name` for `TimeoutError` first |
Exercise
A caller passes a signal to fetchJson with timeoutMs set to 3000, then calls controller.abort() after 1 second. What is err.name in the caller's catch block, and does the "Timed out" error get thrown?
Show answer
err.name is "AbortError". The caller's signal aborted first, so the combined signal takes its reason, a DOMException named AbortError. The TimeoutError branch never runs, so fetchJson rethrows the original error unchanged.
Exercise
Why does fetchJson skip AbortSignal.any() when no signal is passed in, and what would happen if it called AbortSignal.any([undefined, timeoutSignal]) instead?
Show answer
With only one source, the timeout signal can be used directly. Passing undefined inside the array throws a TypeError, because every entry given to AbortSignal.any() must be an AbortSignal.