Conditional callback execution

What is the best way to eliminate the following control:

  • I only want to call getSomeOtherDataif it someDataequals 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();
           });
       });
   });
});           
+5
source share
2 answers

There is no great solution; the best I have found is to create a local function that will do the rest of the overall work as follows:

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();
    }
  });
}); 
+3
source

This is what you need?

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();
            });
        });
    });
});
+2
source

All Articles