TaskSignal: any() 静态方法
TaskSignal.any()
静态方法接收一个 AbortSignal
对象的可迭代对象,并返回一个 TaskSignal
。当任何一个中止信号被中止时,返回的任务信号将被中止。
当任务信号被中止时,其 reason
属性将被设置为第一个被中止的信号的原因。
语法
js
TaskSignal.any(signals)
TaskSignal.any(signals, init)
参数
返回值
示例
使用 TaskSignal.any()
此示例演示了如何结合来自 TaskController
的信号和来自 TaskSignal.timeout()
的超时信号。
js
const cancelDownloadButton = document.getElementById("cancelDownloadButton");
const userCancelController = new TaskController({
priority: "user-visible",
});
cancelDownloadButton.addEventListener("click", () => {
userCancelController.abort();
});
// Timeout after 5 minutes
const timeoutSignal = TaskSignal.timeout(1_000 * 60 * 5);
// This signal will abort when either the user clicks the cancel button or 5 minutes is up whichever is sooner
const combinedSignal = TaskSignal.any([
userCancelController.signal,
timeoutSignal,
]);
try {
const res = await fetch(someUrlToDownload, {
// Stop the fetch when any of the
signal: combinedSignal,
});
const body = await res.blob();
// Do something with downloaded content
// ...
} catch (e) {
if (e.name === "AbortError") {
// Cancelled by the user
} else if (e.name === "TimeoutError") {
// Show user that download timed out
} else {
// Other error, e.g. network error
}
}
规范
规范 |
---|
优先级任务调度 # dom-tasksignal-any |
浏览器兼容性
BCD 表格仅在启用 JavaScript 的浏览器中加载。