2

Ex:

function myFunc(args ...){
  ...
  return Promise.all(myPromisesArray)
}

If a promise inside myPromisesArray fails, i will only get the rejection reason in the return value.

Is there a way to recover all the other resolved values?

Tiago Bértolo
  • 3,874
  • 3
  • 35
  • 53
  • Do you control the promises that you are executing? – synthet1c Oct 01 '16 at 16:43
  • The result? No it is arbitrary. – Tiago Bértolo Oct 01 '16 at 16:44
  • No I mean are you writing the code for the promises. If you are don't call the reject function and just return the result. Promises will fail and stop executing as soon as something fails – synthet1c Oct 01 '16 at 16:46
  • Ah no. I dont have that control. – Tiago Bértolo Oct 01 '16 at 16:46
  • 1
    Several solutions here: [ES6 Promise.all() error handle - Is .settle() needed?](http://stackoverflow.com/questions/36605253/es6-promise-all-error-handle-is-settle-needed/36605453#36605453). – jfriend00 Oct 01 '16 at 17:07
  • Possible duplicate of [Does JavaScript Promise.all have a callback that is fired when there are success AND failures](http://stackoverflow.com/questions/32978838/does-javascript-promise-all-have-a-callback-that-is-fired-when-there-are-success) – jib Oct 02 '16 at 01:19

1 Answers1

5

If you're using Q, then there's a function called Q.allSettled that basically does what you ask for.

Otherwise, this simple function will give you the results of all promises, and tell you whether the succeeded or failed. You can then do whatever you need to do with the promises that succeeded or failed.

/**
 * When every promise is resolved or rejected, resolve to an array of
 * objects
 *   { result: [ Promise result ], success: true / false }
**/
function allSettled(promises) {
  return Promise.all(
    promises.map(
      promise => promise.then(
        // resolved
        (result) => ({ result: result, success: true }),
        // rejected
        (result) => ({ result: result, success: false })
      )
    )
  );
}

// example usage:
const one = Promise.resolve(1);
const two = Promise.reject(2);
const three = Promise.resolve(3);

allSettled([ one, two, three ])
  .then((results) => {
    console.log(results[0]); // { result: 1, success: true }
    console.log(results[1]); // { result: 2, success: false }
    console.log(results[2]); // { result: 3, success: true }
  });
Frxstrem
  • 38,761
  • 9
  • 79
  • 119