Search code examples
node.jsasynchronouscallbackcontrol-flow

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

Solution

  • 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();
        }
      });
    });