承诺控制流程 - 捕获与onRejected

时间:2016-02-18 20:51:40

标签: javascript node.js promise es6-promise

我目前想知道为什么这个ES6本机Promise设置中的抛出没有到达catch块

new Promise(function(resolve,reject){

    reject('bar')

}).then(function resolved(){

    console.log('resolved 1');

}, function rejected(){

    console.log('rejected 1')
    throw new Error();

}).then(function resolved(val){

    console.log('resolved 2');

}, function rejected(){

    console.log('rejected 2');

}).catch(function(err){

    console.log('catch');

});

我正在寻找一种方法来获取catch块的控制流,但是如果我使用被拒绝的处理程序,如果我抛出错误,控件就会在那里结束,而不是在catch中。

简单来说,我正在寻找一种方法来结束catch块,即使有一个onRejected处理程序......有没有办法做到这一点?

new Promise(function(resolve,reject){

    throw new Error(); // this goes to onRejected
    reject('bar'); // this goes to onRejected


}).then(function onResolved(){

    console.log('resolved');

}, function onRejected(){

    console.log('rejected')


}).catch(function(err){

    console.log('catch');

});

我的目标是根据是否抛出错误与是否调用拒绝来单独分支。不确定是否可能。也许有一种方法可以明确地调用catch? 我想找到一种方法来做到这一点,如果可能的话,不要在最终的onRejected处理程序中明确地抛出新错误。

这是我的目标,有评论:

new Promise(function(resolve,reject){

    if(success){
       resolve('success');   //this goes to next onResolved
    }
    else if(fail){
       reject('fail');      //this goes to next onRejected (or catch if there is no onRejected)
    }
    else {
       throw new Error('Fatal');  //this goes to next catch
    }

});

这就是我正在寻找的行为

1 个答案:

答案 0 :(得分:3)

错误未到达.catch()的原因是由于在onRejected内处理错误。

onRejected

中再次将.catch()内处理的错误传递给已链接的throw onRejected错误



new Promise(function(resolve,reject){

    throw new Error(); // this goes to onRejected
    reject('bar'); // this goes to onRejected


}).then(function onResolved(){

    console.log('resolved');

}, function onRejected(err){

    console.log('rejected')
    throw err

}).catch(function(err){

    console.log(err, 'catch');

});




修改,更新

在链接onRejected之前.catch()添加.then()之前处理错误



var success = 0,
  fail;

var p = new Promise(function(resolve, reject) {

  if (success) {
    resolve('success'); //this goes to next onResolved
  } else if (fail) {
    reject('fail'); //this goes to next onRejected (or catch if there is no onRejected)
  } else {
    throw new Error('Fatal'); //this goes to next catch
  }

});

p.catch(function(err) {
    console.log("error handled within catch:", err)
})
.then(function(data) {
    // error handled, `p` is now `resolved`
    console.log("resolved", data)
  }, function(err) {
    console.log("rejected", err)
})