一次运行多个函数调用。但如果一个完成,则终止所有运行功能

问题描述 投票:-1回答:1

所以我有5个功能,我需要立即运行它。但是在一个函数完成后终止所有函数。有可能的?我搜索过但没有找到任何与我的问题相关的答案。

javascript node.js
1个回答
0
投票

你可以使用Promise.race


Promise.race的示例

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

function func() {
  return new Promise((resolve) => {
    const time = getRandomInt(1000, 3000);

    console.log(`Function terminate in ${time} ms`);

    setTimeout(() => resolve(), time);
  });
}

let time = Date.now();

(async() => {
  const time = Date.now();

  await Promise.race([
    func(),
    func(),
    func(),
  ]);

  console.log(`Over after ${Date.now() - time} ms`);
})();

Promise.all的示例

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

function func() {
  return new Promise((resolve) => {
    const time = getRandomInt(1000, 3000);

    console.log(`Function terminate in ${time} ms`);

    setTimeout(() => resolve(), time);
  });
}

(async() => {
  let time = Date.now();

  await Promise.all([
    func(),
    func(),
    func(),
  ]);

  console.log(`Over after ${Date.now() - time} ms`);
})();
© www.soinside.com 2019 - 2024. All rights reserved.