Skip to content
jshacks.dev
Async

How to Combine AbortSignals From Multiple Sources

Combine AbortSignals from multiple sources with AbortSignal.any, add a timeout, read the abort reason and use a fallback for runtimes that lack the method.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Redis, Apache Kafka and RabbitMQ logos.

One request often has several reasons to stop. The user may press cancel, a deadline may pass, the page may navigate away, or the server may be shutting down. Each reason has its own AbortSignal, and the function doing the work accepts exactly one. Passing only one of them means the others are ignored. The answer is to combine abort signals into one that fires when any source fires. Modern runtimes do this with AbortSignal.any(), and a short helper covers the rest. This post shows how to combine abortsignals from several sources in Node.js 24 and current browsers, how the combined signal reports its reason, which timer and event helpers to use and what to watch for with lifetimes. It builds on implementing a cancelable promise, which explains the single-signal case.

AbortSignal.any

AbortSignal.any(signals) takes an iterable of signals and returns a new signal. The new signal aborts as soon as any of the inputs aborts, with the same reason as that input. If one of the inputs is already aborted, the new signal is aborted at once. It is available in Node.js 20.3 and later, and in Chrome 116, Firefox 124 and Safari 17.4 and later.

any.jsJavaScript
const userCancel = new AbortController();
const shutdown = new AbortController();

const signal = AbortSignal.any([userCancel.signal, shutdown.signal]);

signal.addEventListener("abort", () => {
  console.log("aborted:", signal.reason.message);
});

shutdown.abort(new Error("server is shutting down"));
console.log(signal.aborted);
Text
aborted: server is shutting down
true

The combined signal inherited the reason from the source that fired. Because the listener runs synchronously inside abort(), its message prints before the next line. Code that receives the combined signal needs no knowledge of how many sources exist.

Add a deadline

The most common second source is a timeout. AbortSignal.timeout(ms) creates a signal that aborts after the delay with a TimeoutError. Combining it with the user's signal gives "stop on cancel or after five seconds".

with-timeout.jsJavaScript
async function fetchWithLimits(url, userSignal) {
  const signal = AbortSignal.any([userSignal, AbortSignal.timeout(5000)]);
  const response = await fetch(url, { signal });
  return response.json();
}

const user = new AbortController();
const pending = fetchWithLimits("https://api.example.test/report", user.signal);
user.abort();

try {
  await pending;
} catch (error) {
  console.log(error.name);
}
Text
AbortError

The user canceled immediately, so the reason is the default AbortError. If five seconds had passed first, the rejection would have been a TimeoutError. That difference is how the calling code decides whether to show "canceled" or "took too long". The timer behind AbortSignal.timeout does not keep the Node.js process alive, so an unused timeout signal does not delay exit.

Tell the reasons apart

Each source should produce a distinguishable reason. A function that handles the failure inspects signal.reason, which is a DOMException named AbortError or TimeoutError, or whatever value was passed to abort(reason).

reasons.jsJavaScript
function describe(signal) {
  const reason = signal.reason;
  if (reason?.name === "TimeoutError") return "deadline passed";
  if (reason?.name === "AbortError") return "canceled by the user";
  return `stopped: ${reason}`;
}

const a = new AbortController();
a.abort();
console.log(describe(a.signal));

console.log(describe(AbortSignal.abort(new Error("shutdown"))));

const t = AbortSignal.timeout(1);
await new Promise((resolve) => setTimeout(resolve, 20));
console.log(describe(t));
Text
canceled by the user
stopped: Error: shutdown
deadline passed

AbortSignal.abort(reason) creates a signal that is already aborted, which is useful in tests and for the "cancel before starting" case. When you throw your own reason, make it an Error subclass with a clear name, such as ShutdownError, and match on it. Matching on message text breaks when the wording changes.

Throw the reason with throwIfAborted

Inside the work, check the signal at natural pause points and stop with the reason attached. signal.throwIfAborted() throws signal.reason if the signal has fired, and does nothing otherwise.

loop.jsJavaScript
async function processAll(items, signal) {
  const done = [];
  for (const item of items) {
    signal.throwIfAborted();
    await new Promise((resolve) => setTimeout(resolve, 5));
    done.push(item);
  }
  return done;
}

const controller = new AbortController();
setTimeout(() => controller.abort(new Error("stop now")), 12);

try {
  await processAll([1, 2, 3, 4, 5, 6], controller.signal);
} catch (error) {
  console.log(error.message);
}
Text
stop now

The loop stopped between items, not in the middle of one, which keeps each unit of work whole. For work that has no natural pause, such as a long synchronous computation, a signal cannot interrupt it, and you have to check it every so many iterations.

A fallback for older runtimes

If you need to support an environment without AbortSignal.any, build the combination yourself: create a controller, listen to each source and abort the controller when one fires. Clean up the listeners afterward, or long-lived signals accumulate handlers.

any-fallback.jsJavaScript
export function anySignal(signals) {
  if (typeof AbortSignal.any === "function") return AbortSignal.any(signals);

  const controller = new AbortController();
  const cleanups = [];

  const abort = (source) => {
    cleanups.forEach((fn) => fn());
    controller.abort(source.reason);
  };

  for (const source of signals) {
    if (source.aborted) {
      abort(source);
      break;
    }
    const listener = () => abort(source);
    source.addEventListener("abort", listener, { once: true });
    cleanups.push(() => source.removeEventListener("abort", listener));
  }
  return controller.signal;
}

const a = new AbortController();
const b = new AbortController();
const signal = anySignal([a.signal, b.signal]);
b.abort(new Error("from b"));
console.log(signal.aborted, signal.reason.message);
Text
true from b

The native version also handles a subtle case that matters for memory. A hand-written combination holds references to its sources through the listeners, so a signal that is never aborted keeps them alive. AbortSignal.any is built so that the combined signal can be garbage collected when nothing refers to it, which is a good reason to use it when it exists.

Lifetimes and leaks

Every listener you add to a long-lived signal, such as one that represents the whole application's shutdown, stays until the signal is collected or the listener is removed. Adding a listener for each request on that signal grows memory with the request count. Prefer to derive a short-lived combined signal per request with AbortSignal.any([appShutdown, requestTimeout]), and let it be collected when the request ends. Where you must add listeners manually, use { once: true } and remove them in a finally block.

A request-scoped pattern

In a server, the useful combination is application shutdown, client disconnect and a per-request deadline. Create one controller for the application, abort it from the shutdown handler, and for each request build a signal with AbortSignal.any from three inputs: the application signal, a signal that aborts when the client connection closes, and AbortSignal.timeout with the request's budget. Pass that signal down to every database call, fetch and file read the request makes. When the client leaves, everything in flight for that request stops, and when the server is shutting down, every request stops with a reason that says so.

This pattern also gives you one place to decide the status code. A TimeoutError maps to 504, a client disconnect needs no response at all and a shutdown maps to 503. Because the reasons are distinct, the error handler is a small switch on reason.name, and the rest of the code stays free of status logic.

Passing the signal through layers

A signal helps only if each layer forwards it. A function that accepts a signal but calls a helper without passing it breaks the chain, and the helper keeps working after the caller gave up. Make the signal a named option in every async function in the call path, usually the last parameter as { signal }, and forward it unchanged. Review code for the common slip: a new helper added in the middle of the path with no signal parameter. A lint rule or a code review habit of searching for fetch( and await calls without a signal catches most of them.

When a layer does its own timeout, combine instead of replacing. If a function must retry up to three times, each attempt can have its own short timeout combined with the caller's signal, so the caller's cancel still stops the whole sequence immediately, while each attempt is bounded on its own.

Testing combined signals

The pure logic is easy to test because signals are plain objects you can abort by hand. Build a combined signal from two controllers, abort the second with a custom reason and assert on signal.aborted and signal.reason. Test the already-aborted input by passing AbortSignal.abort() and asserting the result is aborted before any event fires. For the timeout source, use a real but very short deadline of a few milliseconds and await it, since AbortSignal.timeout does not run through the global setTimeout that mock timers replace, or inject the timeout signal as a parameter and pass a controller you abort by hand. Add a test for cleanup in the fallback helper, by aborting one source and confirming that listeners on the others were removed, so nothing leaks when the combination is used for thousands of requests.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.