Promise: Ignore Catch and Return to Chain

2019-04-20 22:18发布

问题:

Is it possible to ignore a catch and return back to the chain?

promiseA()        // <-- fails with 'missing' reason
  .then(promiseB) // <-- these are not going to run 
  .then(promiseC)
  .catch(function(error, ignore){
     if(error.type == 'missing'){
        ignore()  // <-- ignore the catch and run promiseB and promiseC
     }
  })

Is something like this possible?

回答1:

Here's the synchronous analogy:

try {
  action1(); // throws
  action2(); // skipped
  action3(); // skipped
} catch (e) {
  // can't resume
}

vs

try {
  action1(); // throws
} catch (e) {
  handleError(e);
}
action2(); // executes normally
action3();

Here's the promise version:

asyncActionA()        // <-- fails with 'missing' reason
.catch(error => {
   if(error.type == 'missing'){
      return; // Makes sure the promise is resolved, so the chain continues
   }
   throw error; // Otherwise, rethrow to keep the Promise rejected
})
.asyncActionB(promiseB) // <-- runs
.asyncActionC(promiseC)
.catch(err => {
  // Handle errors which are not of type 'missing'.
});


回答2:

If you need just ignore all error in promiseA, you can just do it like that:

promiseA()  
  .catch(function(error){
      //just do nothing, returns promise resolved with undefined
  })  
  .then(promiseB)
  .then(promiseC) 

If you need to run promiseB only when error.type == 'missing', you can do that:

promiseA()       
  .catch(function(error, ignore){
     if(error.type == 'missing'){
        return promiseB.then(promiseC)  
     }
  })