蓝鸟承诺:嵌套或条件链

时间:2015-06-16 21:01:42

标签: javascript promise bluebird

我将Bluebird Promises用于Node.js应用程序。如何为我的应用程序引入条件链分支?示例:

exports.SomeMethod = function(req, res) {
        library1.step1(param) 
        .then(function(response) { 
            //foo

            library2.step2(param)
            .then(function(response2) { //-> value of response2 decides over a series of subsequent actions
                if (response2 == "option1") {
                    //enter nested promise chain here?
                    //do().then().then() ...
                }

                if (response2 == "option2") {
                    //enter different nested promise chain here?
                    //do().then().then() ...
                }

               [...]
            }).catch(function(e) { 
                //foo
            });
    });
};

除了没有找到这个的工作版本之外,这个解决方案感觉(并且看起来)不知何故。我有点怀疑我有点违反承诺的概念或类似的东西。任何其他建议如何引入这种条件分支(每个特征不是一个,而是许多后续步骤)?

2 个答案:

答案 0 :(得分:4)

是的,你可以这样做,就像那样。重要的是从(回调)函数始终return承诺

exports.SomeMethod = function(req, res) {
    return library1.step1(param)
//  ^^^^^^
    .then(function(response) { 
        … foo

        return library2.step2(param)
//      ^^^^^^
        .then(function(response2) {
            if (response2 == "option1") {
                // enter nested promise chain here!
                return do().then(…).then(…)
//              ^^^^^^
            } else if (response2 == "option2") {
                // enter different nested promise chain here!
                return do().then(…).then(…)
//              ^^^^^^
            }
        }).catch(function(e) { 
            // catches error from step2() and from either conditional nested chain
            …
        });
    }); // resolves with a promise for the result of either chain or from the handled error
};

答案 1 :(得分:0)

只需在.then()处理程序中返回其他承诺,如下所示。关键是从.then()处理程序中返回一个promise,并自动将其链接到现有的promise中。

exports.SomeMethod = function(req, res) {
        library1.step1(param) 
        .then(function(response) { 
            //foo

            library2.step2(param)
            .then(function(response2) { //-> value of response2 decides over a series of subsequent actions
                if (response2 == "option1") {
                    // return additional promise to insert it into the chain
                    return do().then(...).then(...);
                } else if (response2 == "option2") {
                    // return additional promise to insert it into the chain
                    return do2().then(...).then(...);
                }

               [...]
            }).catch(function(e) { 
                //foo
            });
    });
};