Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bluebird Promise: Nested or conditional chains

I use Bluebird Promises for a Node.js application. How can I introduce conditional chain branches for my application? Example:

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

Apart from not having figured out a working version of this yet, this solution feels (and looks) weird somehow. I got a sneaking suspicion that I am somewhat violating the concept of promises or something like that. Any other suggestions how to introduce this kind of conditional branching (each featuring not one but many subsequent steps)?

like image 980
Igor P. Avatar asked Jan 02 '26 07:01

Igor P.


1 Answers

Yes, you can do it, just like that. The important thing is just to always return a promise from your (callback) functions.

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
};
like image 193
Bergi Avatar answered Jan 06 '26 10:01

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!