用Javascript/ECMAScript 6等待多个承诺(Promise)

3

我想要开始一个承诺列表,并在所有承诺完成时执行回调函数(不使用async/await)。

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

@AdrianHeine - 在OP能够接受自己的答案之前,您必须等待相当长的时间(我忘记了确切的时间)。 - jfriend00

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接