Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditionally executing a callback

What's the best way to solve the following control flow niggle:

  1. I only want to call getSomeOtherData if someData is equal to some value / passes some conditional test

  2. 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();
           });
       });
   });
});           
like image 523
cjroebuck Avatar asked Feb 18 '13 21:02

cjroebuck


People also ask

How callback function is executed?

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.

Does taking a callback make a function asynchronous?

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.

When callback is executed?

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 .

Are all callbacks Asynchronous?

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.


1 Answers

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();
    }
  });
}); 
like image 94
JohnnyHK Avatar answered Sep 27 '22 22:09

JohnnyHK