蓝鸟 - 如何尽早打破承诺链

时间:2016-05-09 08:36:54

标签: node.js promise bluebird

PromiseA().then(function(dataA){
    if (dataA.foo == "skip me")
        return ?? //break promise early - don't perform next then()
    else
        return PromiseB()
}).then(function(dataB){
    console.log(dataB)
}).catch(function (e) {
    //Optimal solution will not cause this method to be invoked
})

如何修改上述代码以提前破解(跳过第二个然后())?

1 个答案:

答案 0 :(得分:9)

Bluebird允许cancel a promise

var Promise = require('bluebird');
Promise.config({
    // Enable cancellation
    cancellation: true,
});

// store the promise
var p = PromiseA().then(function(dataA){
    if (dataA.foo == "skip me")
        p.cancel(); // cancel it when needed
    else
        return PromiseB();
}).then(function(dataB){
    console.log(dataB);
}).catch(function (e) {
    //Optimal solution will not cause this method to be invoked
});