Reputation: 2263
What's the best way to solve the following control flow niggle:
I only want to call getSomeOtherData
if someData
is equal to some value / passes some conditional test
In both cases I always want to call getMoreData
http.createServer(function (req, res) {
getSomeData(client, function(someData) {
// Only call getSomeOtherData if someData passes some conditional test
getSomeOtherData(client, function(someOtherData) {
// Always call getMoreData
getMoreData(client, function(moreData) {
res.end();
});
});
});
});
Upvotes: 5
Views: 587
Reputation: 2493
Is this something you want?
http.createServer(function (req, res) {
getSomeData(client, function(someData) {
function myFunction (callback) {
// Only call getSomeOtherData if someData passes some conditional test
if (someData) {
getSomeOtherData(client, function(someOtherData) {
// Do something.
});
}
callback();
}
myFunction(function () {
// Always call getMoreData
getMoreData(client, function(moreData) {
res.end();
});
});
});
});
Upvotes: 2
Reputation: 311855
No great solution to this; the best I've found is to make a local function that takes care of the remaining common work like this:
http.createServer(function (req, res) {
getSomeData(client, function(someData) {
function getMoreAndEnd() {
getMoreData(client, function(moreData) {
res.end();
});
}
if (someData) {
getSomeOtherData(client, function(someOtherData) {
getMoreAndEnd();
});
} else {
getMoreAndEnd();
}
});
});
Upvotes: 3