AbortSignal.any Combines Cancel Sources
Merge several AbortControllers into one downstream signal with AbortSignal.any so a cancel from any source reaches every consumer with the original reason.
Code
// AbortSignal.any: 多个取消来源合并成一个下游信号
const userCancel = new AbortController();
const policyDeadline = new AbortController();
const combined = AbortSignal.any([userCancel.signal, policyDeadline.signal]);
combined.addEventListener('abort', () => {
const reason = combined.reason;
console.log('cancelled:', reason instanceof Error ? reason.message : String(reason));
});
console.log('before:', combined.aborted);
policyDeadline.abort(new Error('deadline exceeded'));
console.log('after:', combined.aborted);
// 放开下一行同样会让 combined 变为 aborted:任一来源触发即可
// userCancel.abort(new Error('user clicked stop'));
async function waitUntil(cancel: AbortSignal): Promise<string> {
if (cancel.aborted) throw cancel.reason; // 已取消时直接失败
return 'started';
}
waitUntil(combined)
.then((message) => console.log(message))
.catch((error: unknown) => {
console.log('wait failed:', error instanceof Error ? error.message : String(error));
});Output
Captured from a sandboxed run of this snippet in the build pipeline.
before: false
cancelled: deadline exceeded
after: true
wait failed: deadline exceededHow it works
Beyond the waitUntil consumer, the setup is three lines: two AbortController sources, one AbortSignal.any([...]) merge, and an abort listener that reports combined.reason.
Await points sequence the asynchronous work; a rejection lands at the awaiting line.
Points of care
- The guard
cancel.abortedshort-circuits the flow with an earlythrowwhen its condition holds.
Using it
Entry signature: async function waitUntil(cancel: AbortSignal)
policyDeadline.abort(new Error('deadline exceeded')) flips the merged signal mid-run, so the output walks the state change in order: before: false, cancelled: deadline exceeded, after: true, then wait failed: deadline exceeded.
Key statements
combined.addEventListener('abort', () => {
const reason = combined.reason;
console.log('cancelled:', reason instanceof Error ? reason.message : String(reason));
});
.catch((error: unknown) => {
console.log('wait failed:', error instanceof Error ? error.message : String(error));
});
async function waitUntil(cancel: AbortSignal): Promise<string> {
if (cancel.aborted) throw cancel.reason; // 已取消时直接失败
return 'started';
}
Interactive Tools for This Topic
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. The file defines `waitUntil` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.