Bluebird - 如何传播嵌套承诺中的错误

Bluebird - how to propagate errors in nested promise

PromiseA().then(function(){
    PromiseB().catch(function (e) {
        throw e;
    })
}).catch(function (e) {
    // I want exceptions thrown in the nested promise chain to end up here.
})

如何从嵌套承诺中获取异常以冒泡到父承诺?

使用return关键字,

您的代码可以简化为:

PromiseA().then(function(){
    return PromiseB();
}).catch(function (e) {
    // I want exceptions thrown in the nested promise chain to end up here.
})

编辑:

不确定这是否是正确的方法,但如果涉及取消承诺并且您只想冒泡错误流,您可以将您的承诺包装在自定义承诺中,它永远不会解决但会抛出错误(如果发生) :

PromiseA().then(function(){
    var myPromise = PromiseB().then...;
    return new Promise(function(resolve, reject){
      myPromise.catch(reject)
    })
}).catch(function (e) {
    // I want exceptions thrown in the nested promise chain to end up here.
})

首先,避免使用嵌套的承诺。也总是使用 return 语句来 return 承诺嵌套函数的结果。在您的示例中,从未使用 PromiseB 结果,并且将在解决 PromiseB 之前解决主承诺链。

在您目前的情况下,您可以使用 Promise.reject 函数将错误冒泡到父承诺:

PromiseA()
    .then(function() {
        return PromiseB()
            .catch(function (err) {
                // TODO: error processing
                return Promise.reject(err);
            });
    })
    .catch(function(err) {
        // Here you'll get the same err object as in first catch
    });