yokomizor
yokomizor

Reputation: 1577

Await more than one promise with Javascript / ECMAScript 6

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

Upvotes: 3

Views: 148

Answers (2)

Dale Jefferson
Dale Jefferson

Reputation: 1910

Yes, Promise.all is your friend here.

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

Any reason why 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/

Upvotes: 0

yokomizor
yokomizor

Reputation: 1577

I have just figured out. 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);
  });
})();

Upvotes: 4

Related Questions