Search code examples
javascriptes6-promise

Filter/recover Promise.all result


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?


Solution

  • 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 }
      });