Why is onRejected not called following Promise.all() where Promise.reject() included in array passed to Promise.all()?

Given

var promises = [Promise.resolve("a"), Promise.reject("b")];

Promise.all(promises.map(function(p, index) {
  return p.then(function(data) {
    console.log("inside .map()", data, "index", index)
    return data
  }, function(err) {
    console.log(err);
    return err
  })
}))
.then(function(complete) {
  console.log("all promises after .map()", complete)
}, function(err) {
  console.log("err", err)
})

why is onRejected not called at .then(onFulfilled, onRejected) following Promise.all() ?

jsfiddle https://jsfiddle.net/9gprLc7q/

https://jsfiddle.net/9gprLc7q/


You need to understand that handling a rejection results in putting the promise back on the success path. One approach to this is to re-throw in the failure handler, like this:

var promises = [Promise.resolve("a"), Promise.reject("b")];

Promise.all(promises.map(function(p, index) {
  return p.then(function(data) {
    console.log("inside .map()", data, "index", index)
    return data
  }, function(err) {
    console.log(err);

    // RE-THROW!!
    throw err;                  

  })
}))
.then(...

If the purpose of the rejection handler is merely to log, then you could move it out of the chain:

Promise.all(promises.map(function(p, index) {

  // MOVE ERROR HANDLER OUTSIDE OF CHAIN
  p.catch(function(e) { console.log(e); });

  return p.then(function(data) {
    console.log("inside .map()", data, "index", index)
    return data
  })
}))
.then(...

What you've really done here is something like this:

https://jsfiddle.net/9gprLc7q/5/

var notRejectedPromise = 
    Promise.reject("b")
      .then((resolved) => resolved, (err) => err)

var promises = [Promise.resolve("a"), notRejectedPromise];

Promise.all(promises)
.then(function(complete) {
  console.log("all promises after .map()", complete)
}, function(err) {
  console.log("err", err)
})

But deciding to handle the err portion by returning whatever err was, you returned a string. This is not a reason for rejection.

To actually cause the Promise.all() to reject you need an error to occur in either the resolved or rejected portion of .then

Given this, if you return a rejected promise, it will reject:

https://jsfiddle.net/9gprLc7q/3/

console.log(err)

to

return Promise.reject(err)

Alternatively you can throw an error: https://jsfiddle.net/9gprLc7q/2/

console.log(err)

to

throw new Error(err)