How can we use Promise.all(iteratable)?

javascript-promises

There are times when we want to trigger multiple independent asynchronous calls but only want to respond when all of them are completed. That is when we need to use the Promise.all method, which takes an array of promises, and invoke its callback when all of these promises are resolved:

Promise.all([promise1, promise2])
  .then(function(results) {
    // Both promises were resolved.
  })
  .catch(function(error) {
    // One or more promises was rejected
  });
);

In the above code, results (the parameter of the then callback) is an array containing the results of the last then callback of each of the promises that were passed to Promise.all.

The Promise.all method returns a promise that either fulfills when all of the promises in the iterable argument have fulfilled or rejects as soon as one of the promises in the iterable argument rejects. If the returned promise fulfills, it is fulfilled with an array of the values from the fulfilled promises in same order as defined in the iterable. If the returned promise rejects, it is rejected with the reason from the first promise in the iterable that rejected. This method can be useful for aggregating results of multiple promises.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License