实现说明
除了函数 work,文件里再无其他定义。
await 点把异步工作排成序列,拒绝落在取结果的那一行。
使用要点
- 跑完文件,输出里会留下标记——
combined aborted, reason:、work stopped with:。
常见问题
有第三方依赖吗?
没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 work。
签名一览: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 });
});
combined.addEventListener("abort", () => {
console.log("combined aborted, reason:", combined.reason.name);
});
setTimeout(() => controller.abort(new DOMException("user closed tab", "AbortError")), 50);
代码示例
// 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);
}