Promise 控制流 - catch 与 onRejected

Promise control flow - catch versus onRejected

我目前想知道为什么这个 ES6 原生 Promise 设置中的 throw 没有到达 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');

});

我的目标是根据是否抛出错误与是否调用 reject 分别进行分支。不确定是否可能。也许有一种方法可以显式调用 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
    }

});

这就是我要寻找的行为

错误未到达 .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 之前处理错误,请在链式 .then() 之前添加 .catch()

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)
})