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();
});
});
});
});
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.
Simply taking a callback doesn't make a function asynchronous. There are many examples of functions that take a function argument but are not asynchronous. For example there's forEach in Array.
The order in which listeners callback functions execute after the firing of an event is undefined. However, all listener callbacks execute synchronously with the event firing. The handle class notify method calls all listeners before returning execution to the function that called notify .
The function that takes another function as an argument is called a higher-order function. According to this definition, any function can become a callback function if it is passed as an argument. Callbacks are not asynchronous by nature, but can be used for asynchronous purposes.
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();
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With