AbortSignal Any Combines Cancellation Sources

AbortSignal.any merges several cancellation sources into one signal, so a parent controller aborts a running loop the moment any source fires.

JavascriptResilience

Code

javascriptsnippet
34 lines
// 多个取消来源合并成一个信号(cancellation sources):任一来源 abort,组合信号同步转为 aborted
const userAbort = new AbortController();
const parentTask = new AbortController();
const combined = AbortSignal.any([userAbort.signal, parentTask.signal]);

combined.addEventListener('abort', () => {
  console.log('combined aborted by:', combined.reason.message);
});

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// 每个异步步骤之间检查组合信号,而不是等操作失败后才知道被取消
async function scan(files, signal) {
  const done = [];
  for (const file of files) {
    signal.throwIfAborted(); // 已中止时抛出 reason,循环立即终止
    done.push(file);
    console.log('scanned:', file);
    await sleep(5);
  }
  console.log('all files scanned');
  return done;
}

const running = scan(['a.log', 'b.log', 'c.log'], combined);
// 父任务取消:userAbort 自身未触发,但组合信号同样中止
parentTask.abort(new Error('parent cancelled'));
try {
  await running;
} catch (reason) {
  console.log('scan stopped with:', reason.message);
}
console.log('userAbort.aborted:', userAbort.signal.aborted);
console.log('combined.aborted:', combined.aborted);

Output

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

scanned: a.log
combined aborted by: parent cancelled
scan stopped with: parent cancelled
userAbort.aborted: false
combined.aborted: true

How it works

AbortSignal Any Combines Cancellation Sources comes down to the functions sleep and scan.

Repetition is confined to for (const file of files) — the rest of the file is straight-line. Await points sequence the asynchronous work; a rejection lands at the awaiting line.

Applying it

The primary signature is const sleep = (ms)

The run emits 5 labeled sections — combined aborted by:, scanned:, scan stopped with:, userAbort.aborted:, combined.aborted: — one per step.

Statements that matter

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
combined.addEventListener('abort', () => {
  console.log('combined aborted by:', combined.reason.message);
});
const parentTask = new AbortController();

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 `sleep`, `scan` at load time.