一次运行多功能调用。但如果完成则终止所有正在运行的功能

时间:2018-07-18 11:01:06

标签: javascript node.js

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

1 个答案:

答案 0 :(得分: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`);
})();