用 AbortController
,例子:
async function app() {
const wait1 = function (signal) {
return new Promise((resolve) => {
const id = setTimeout(() => {
console.log("wait1");
resolve(1);
}, 1000);
signal.addEventListener("abort", () => {
clearTimeout(id);
resolve(1);
});
});
};
const wait2 = function (signal) {
return new Promise((resolve) => {
const id = setTimeout(() => {
console.log("wait2");
resolve(2);
}, 2000);
signal.addEventListener("abort", () => {
clearTimeout(id);
resolve(2);
});
});
};
const wait = async () => {
const controller = new AbortController();
const duration = await Promise.race([
wait1(controller.signal),
wait2(controller.signal),
]);
controller.abort();
return duration;
};
console.log(await wait());
}
app();
参考文章: