cjroebuck
cjroebuck

Reputation: 2263

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

Upvotes: 5

Views: 587

Answers (2)

dparpyani
dparpyani

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

JohnnyHK
JohnnyHK

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

Related Questions