承诺:忽略捕获并返回链

时间:2016-04-13 11:26:12

标签: javascript promise ignore 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
     }
  })

这样的事情可能吗?

2 个答案:

答案 0 :(得分:16)

以下是同步类比:

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

VS

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

这是承诺版本:

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'.
});

答案 1 :(得分:1)

如果你需要忽略promiseA中的所有错误,你可以这样做:

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

如果您需要仅在error.type == 'missing'时运行promiseB,则可以执行此操作:

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