Skip to content Skip to sidebar Skip to footer

Waiting For Promises To Resolve Within An Array

With an Array of Promises how do I wait until they have all resolved before proceeding? Below is an example implementation, where task_2 is firing it's rejection before task_1 can

Solution 1:

If I understand your question correctly from your comment

It's actually just an example, I am curious as to how you would wait for an array of Promises to resolve/reject, before proceeding. You might have for example an array of Promises which make HTTP calls, in the event of an error, you would want to output all errors rather than the most recent.

you want to wait until all the promises have either been resolved or rejected, and then continue.

Promise.all() will reject if any of the given promises in the array is rejected, thus it is not an alternative for your in this case.

There is an .always() function in jQuery that work like this, and if you were to use BlueBird you could use .reflect() to inspect the promises of the Promise.all(). There is no current function in ES6 that can do this.

Borrowing from the answer of this question, ES6 promise settled callback?, you can implement your own version of .always()/.finally()/.allSettled() like this

Promise.prototype.finally = function(cb) {
    constres = () => thisreturnthis.then(value =>Promise.resolve(cb({state:"fulfilled", value})).then(res)
    , reason =>Promise.resolve(cb({state:"rejected", reason})).then(res)
    );
};

Solution 2:

If i understand your problem correctly i guess you might still use Promise.all() however you have to wrap your promises by a function to handle the rejections separately. I mean you may catch the rejection before it triggers a premature exit of the Promise.all() and handle the rejection by resolving it with a special object.

As an example;

functionhandleRejectedPromises(p){
  returnnewPromise((resolve,reject) => p.then(v =>resolve({status: "resolved", value: v}))
                                          .catch(x =>resolve({status: "rejected", reason: x})));
}
var ps = [Promise.resolve(42), Promise.reject(37), Promise.resolve(23), Promise.resolve(11)];

Promise.all(ps.map(p =>handleRejectedPromises(p)))
       .then(ra => ra.forEach(r =>console.log(r)));

OK as per @Bergi's comment i have to correct my answer accordingly in order to take it off of anti-pattern realm.

functionhandleRejectedPromises(p){
  return p.then(v => ({status: "resolved", value: v}))
          .catch(x => ({status: "rejected", reason: x}));
}
var ps = [Promise.resolve(42), Promise.reject(37), Promise.resolve(23), Promise.resolve(11)];

Promise.all(ps.map(p =>handleRejectedPromises(p)))
       .then(ra => ra.forEach(r =>console.log(r)));

Post a Comment for "Waiting For Promises To Resolve Within An Array"