Sub topic 14
Combining User Cancellation and Timeouts with AbortSignal.any()
Many real functions have more than one reason to stop. The user might click Cancel. The request might run past its deadline. One part of a parallel job might fail, and then the other parts have no reason to keep going. A function takes only one signal option, but fetch and your own cancellable functions also accept only one signal. AbortSignal.any() solves this. It merges several signals into one, and that one signal aborts as soon as any of its inputs does.
This chapter assumes you have read the earlier chapters on signal state, abort reasons, and AbortSignal.timeout(). You should be comfortable with promises, async/await, and try/catch.
What AbortSignal.any() Does
AbortSignal.any(signals) takes an iterable of AbortSignal objects and returns a new signal. This chapter calls it the combined signal. It follows these rules:
- It aborts when the first input signal aborts.
- Its
reasonis the exact same value as that first input'sreason. It is the same object, not a copy. - If any input is already aborted when you call
any(), the combined signal comes back already aborted, with that input's reason. - After it aborts, it stays aborted. Later aborts on other inputs change nothing.
- An empty iterable gives a signal that never aborts.
The Core Pattern: Caller Signal Plus Deadline
The usual case is a function that respects the caller's signal and also enforces its own timeout:
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;
}
}Some details matter here:
- The
signaloption is optional, so the function only callsany()when it actually has a caller signal.AbortSignal.any([undefined, timeoutSignal])throws aTypeError, because every entry must be anAbortSignal. - The combined signal is passed to
fetch, so the request stops for either reason. - The catch block can tell the two causes apart by name. A timeout rejects with a
DOMExceptionnamed"TimeoutError". A caller who callscontroller.abort()with no argument produces"AbortError". If the caller passed a custom reason, that value comes through unchanged and is rethrown.
Caller code stays simple:
const controller = new AbortController();
cancelButton.addEventListener('click', () => controller.abort(), { once: true });
try {
const data = await fetchJson('/api/report', {
signal: controller.signal,
timeoutMs: 3000,
});
render(data);
} catch (err) {
if (err.name === 'AbortError') {
// The user cancelled. Stay quiet.
} else {
showError(err.message); // timeout or a real failure
}
}Which Source Fired?
Checking err.name works when every source has a distinct reason type. Sometimes two sources share a type. For example, you might combine two plain controllers, each aborted with no argument. In that case, ask the source signals directly:
const userController = new AbortController();
const shutdownController = new AbortController();
const combined = AbortSignal.any([userController.signal, shutdownController.signal]);
combined.addEventListener('abort', () => {
if (shutdownController.signal.aborted && combined.reason === shutdownController.signal.reason) {
console.log('stopped because the app is shutting down');
} else {
console.log('stopped by the user');
}
}, { once: true });
shutdownController.abort();The reason identity check (===) is the reliable test. aborted by itself can mislead, because a second source might abort after the first one has already decided the outcome. The cleaner approach is to give each source a meaningful reason when you abort it, for example shutdownController.abort(new Error('Shutting down')). Then the caller never has to inspect sources.
Combining with an Internal Controller
any() is not limited to timeouts. A common pattern pairs the caller's signal with a controller that the function owns. Here a parallel fetch cancels the remaining requests as soon as one fails:
async function fetchAllParallel(urls, { signal } = {}) {
const internal = new AbortController();
const combined = signal
? AbortSignal.any([signal, internal.signal])
: internal.signal;
try {
return await Promise.all(urls.map(async (url) => {
const response = await fetch(url, { signal: combined });
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json();
}));
} catch (err) {
internal.abort(err); // stop the sibling requests
throw err;
}
}Promise.all rejects on the first failure, but by default the other requests keep running and their results are thrown away. Aborting internal stops them. The caller never sees internal. From the outside, the function still accepts one optional signal, like any platform API.
You can nest these signals freely. A combined signal is an ordinary AbortSignal, so you can pass it into another function that combines it again with its own deadline. Each layer adds its own stop condition without knowing about the others.
A Runnable Demonstration
The script below runs in Node 20.3+ or a modern browser console. It reuses the cancellable delay() from an earlier chapter and races a user abort against a timeout:
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 run(userAbortAfterMs, timeoutMs) {
const user = new AbortController();
const combined = AbortSignal.any([user.signal, AbortSignal.timeout(timeoutMs)]);
setTimeout(() => user.abort(), userAbortAfterMs);
try {
await delay(2000, { signal: combined });
console.log('finished');
} catch (err) {
console.log(`stopped: ${err.name}`);
}
}
await run(500, 1000); // stopped: AbortError
await run(1500, 1000); // stopped: TimeoutErrorNotice that delay() needed no changes. A function that handles one signal correctly already handles combined signals.
Gotchas and Edge Cases
The Deadline Starts at Creation
AbortSignal.timeout(ms) starts counting when you call it, not when the work starts. If you create it at the top of a function and then do slow setup before calling fetch, the request gets less time than you meant to give it. Create the timeout right before the work it guards. For retries, create a fresh timeout for each attempt if every attempt gets its own budget. Create one timeout outside the loop if the whole operation shares a single budget.
Already-Aborted Inputs
If the caller passes a signal that is already aborted, any() returns a signal that is already aborted too. Your early aborted check still works, because it reads the combined signal. You don't need to check each source separately.
Order Doesn't Matter, Timing Does
The position of a signal in the array has no effect, except when several inputs are already aborted at call time. In that case, the first aborted one in iteration order supplies the reason.
Memory and Lifetime
The specification has sources hold only weak references to the combined signals that depend on them, and engines may collect a combined signal that nobody can observe any more. You can call any() on every request without building up listeners on a long-lived caller signal. Your own abort listeners are a different matter. Listeners you add to the combined signal still need the cleanup covered in the chapter on cleaning up after abort and after success.
Support and Fallback
AbortSignal.any() is available in Chrome 116+, Firefox 124+, Safari 17.4+, and Node 20.3+. For older runtimes, a small fallback does the same job:
function anySignal(signals) {
const controller = new AbortController();
for (const s of signals) {
if (s.aborted) {
controller.abort(s.reason);
return controller.signal;
}
}
const onAbort = (event) => {
controller.abort(event.target.reason);
for (const s of signals) s.removeEventListener('abort', onAbort);
};
for (const s of signals) s.addEventListener('abort', onAbort);
return controller.signal;
}This fallback holds strong references, so its listeners stay on long-lived sources until one of them aborts. That limitation is why the native version is preferred.
| Approach | Reason preserved | Leaks on long-lived sources | Availability |
|---|---|---|---|
| `AbortSignal.any()` | Yes, same object | No | Modern runtimes |
| Manual `anySignal()` | Yes | Until a source aborts | Everywhere |
| Ignoring the caller's signal | Not applicable | Not applicable | Breaks cancellation |
Exercise
A function calls AbortSignal.any([callerSignal, AbortSignal.timeout(2000)]). The caller aborts at 2500 ms with controller.abort(new Error('closed')). The work would have taken 3000 ms. What is combined.reason, and why?
Show answer
It is a DOMException named "TimeoutError". The timeout aborts at 2000 ms, first, and the combined signal takes that reason. The caller's later abort at 2500 ms has no effect, because a combined signal stays aborted with its first reason.
Exercise
Why does fetchJson check whether signal is defined before calling AbortSignal.any(), instead of always calling AbortSignal.any([signal, timeoutSignal])?
Show answer
Every entry passed to AbortSignal.any() must be an AbortSignal. When the caller omits the option, signal is undefined, and AbortSignal.any() throws a TypeError. Using the timeout signal alone in that case keeps the signal option optional.
Exercise
In fetchAllParallel, what would go wrong if the catch block did not call internal.abort(err)?
Show answer
The function would still reject on the first failure, but the remaining fetch requests would keep running in the background. They would use network and memory for results nobody reads. Aborting the internal controller cancels them through the combined signal.