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

后端 未结 2 1543
借酒劲吻你
借酒劲吻你 2020-11-27 23:23

Given

         


        
相关标签:
2条回答
  • 2020-11-27 23:42

    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)
    
    0 讨论(0)
  • 2020-11-27 23:58

    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(...
    
    0 讨论(0)
提交回复
热议问题