brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: AbortSignal.any() stops a fetch on a timeout or a cancel button, whichever comes first

Javascript
~/tips/tip-js-abortsignal-any-combine

const signal = AbortSignal.any([

Combine several abort reasons into one signal for fetch or any other API.

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()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link