Wait for multiple promises with Javascript / ECMAScript 6

I would like to fire a list of promises and execute a callback when everything is done (no async / await).

+3


source to share


2 answers


I just got it. Just use 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);
  });
})();

      

+4


source


Yes, Promise.all is your friend here.

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

      

Any reason you are not using async / await I find it really simplifies this pattern?



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

      

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

0


source







All Articles