实现说明
真正干活的是函数 sleep、scan,其余都是接线。
for (const file of files) 承担全部的逐项处理。await 标出每个异步边界——没有 fire-and-forget。
使用要点
- 演示输出是带标签的(
combined aborted by:、scanned:、scan stopped with:),每个操作都会留下自己的一行标注。
常见问题
运行之前需要装什么吗?
不需要——用到的每个 API 都随语言运行时自带,无需安装。 文件在加载时定义 sleep、scan。
主签名形如 const sleep = (ms)
核心语句
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
combined.addEventListener('abort', () => {
console.log('combined aborted by:', combined.reason.message);
});
const parentTask = new AbortController();
代码示例
// 多个取消来源合并成一个信号(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);