Bluebird's promise: nested or conditional chains
I am using Bluebird Promises for a Node.js application. How can I inject conditional chaining 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 the fact that I have not yet figured out a working version of this solution, this solution seems (and looks) strange somehow. I have a suspicious suspicion that I am somewhat violating the concept of Promises or something. Any other suggestions on how to introduce such conditional branching (each differing in not one but many subsequent steps)?
source to share
Yes, you can do it just like that. It is important to always make a return
promise from your functions (callbacks).
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
};
source to share
Just return additional promises from your handler .then()
as shown below. The key is to return a promise from the handler .then()
and automatically bind it to existing promises.
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
});
});
};
source to share