Bluebird Promise:嵌套或条件链

Bluebird Promise: Nested or conditional chains

我将 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
            });
    });
};

除了还没有想出这个的工作版本之外,这个解决方案感觉(和看起来)有点奇怪。我偷偷怀疑我在某种程度上违反了承诺的概念或类似的东西。还有其他关于如何引入这种条件分支的建议吗(每个分支都不是一个而是许多后续步骤)?

只是 return 来自你的 .then() 处理程序的额外承诺,如下所示。关键是 return 来自 .then() 处理程序的承诺,并自动将其链接到现有承诺中。

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

是的,你可以做到,就这样。重要的是总是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
};