3

I would like to start a list of promises and execute a callback when all of then are done (without async/await).

4

2 回答 2

4

我刚刚想通了。只需使用 Promise.all:

function x(timeout) {
  return new Promise((resolve, reject) => {
    setTimeout(function() {
      resolve(timeout + ' done!');
    }, timeout);
  });
}

(function() {
  Promise.all([
    x(300),
    x(200),
    x(100),
  ]).then(([x300, x200, x100]) => {
    console.log(x100);
    console.log(x200);
    console.log(x300);
  });
})();
于 2015-04-30T20:31:27.320 回答
0

是的,Promise.all 是你的朋友。

Promise.all([promise1, promise2]).then(([result1, result2]) => {})

为什么你不使用 async/await 我发现它真的简化了这种模式?

const [result1, result2] = await Promise.all([promise1, promise2])

https://www.dalejefferson.com/blog/async-await-promise-all-array-destructuring/

于 2018-02-06T22:04:41.193 回答