AbortSignal.any Merges Timeout With User Cancel

AbortSignal.any fires when the first source aborts and adopts its reason, so a request can honor both a deadline and a user-initiated stop from one signal.

JavascriptResilience

Code

javascriptsnippet
29 lines
// AbortSignal.any: one signal from a timeout plus a user-initiated cancel
const timeout = AbortSignal.timeout(200);
const controller = new AbortController();
const combined = AbortSignal.any([timeout, controller.signal]);

// any() fires when the FIRST source aborts; the reason comes from that source
combined.addEventListener("abort", () => {
  console.log("combined aborted, reason:", combined.reason.name);
});

// user cancel beats the deadline here
setTimeout(() => controller.abort(new DOMException("user closed tab", "AbortError")), 50);

// slow work listens once and reacts to whichever source fired
async function work(signal) {
  return await new Promise((resolve, reject) => {
    const timer = setTimeout(() => resolve("finished"), 5000);
    signal.addEventListener("abort", () => {
      clearTimeout(timer);
      reject(signal.reason);
    }, { once: true });
  });
}

try {
  await work(combined);
} catch (error) {
  console.log("work stopped with:", error.name, error.message);
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

combined aborted, reason: AbortError
work stopped with: AbortError user closed tab

How it works

AbortSignal.any Merges Timeout With User Cancel comes down to the function work.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Using it

Signature: async function work(signal)

Running the file prints labeled results such as combined aborted, reason:, work stopped with: — each operation’s effect is visible in the output.

Key statements

return await new Promise((resolve, reject) => {
const timer = setTimeout(() => resolve("finished"), 5000);
signal.addEventListener("abort", () => {
clearTimeout(timer);
reject(signal.reason);
}, { once: true });
});
combined.addEventListener("abort", () => {
console.log("combined aborted, reason:", combined.reason.name);
});
setTimeout(() => controller.abort(new DOMException("user closed tab", "AbortError")), 50);

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `work` at load time.