logo科技微讯

Promise.race() 结束后如何中断剩余操作

作者:科技微讯
日期:2024-03-04
📝 笔记

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();

参考文章:

donation赞赏
thumbsup0
thumbsdown0
暂无评论