fetch accepts one signal. But often there are two reasons to stop a request: the user clicked Cancel, or it is taking too long. AbortSignal.any() merges them into one.
const controller = new AbortController();
cancelButton.addEventListener("click", () => controller.abort());
const signal = AbortSignal.any([
controller.signal,
AbortSignal.timeout(8000),
]);
try {
const res = await fetch("/api/export", { signal });
// ...
} catch (err) {
if (err.name === "TimeoutError") showMessage("The server took too long.");
else if (err.name === "AbortError") showMessage("Export cancelled.");
else throw err;
}
The combined signal aborts as soon as any of the input signals does, and it takes over that signal’s reason. That makes the error handling neat: the timeout gives a TimeoutError, a manual abort() without an argument gives an AbortError, so I can show a different message for each.
It is not only for fetch. Event listeners, streams and many newer APIs take a signal, and a component can combine its own “unmounted” signal with a per-request one in the same way.
Support: Chrome 116, Firefox 124, Safari 17.4 and Node.js 20.3. One thing to watch: if you pass a reason to abort(reason), that reason is what the fetch rejects with, so the err.name check above no longer sees AbortError.
Further reading: MDN: AbortSignal.any(), MDN: AbortSignal.timeout()