有条件地执行回调

时间:2013-02-18 21:49:01

标签: node.js asynchronous callback control-flow

解决以下控制流程的最佳方法是什么:

  1. 我只想在getSomeOtherData等于某个值时调用someData /通过一些条件测试

  2. 在这两种情况下,我总是想致电getMoreData

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

2 个答案:

答案 0 :(得分:3)

没有很好的解决方案;我发现最好的是创建一个本地函数来处理剩下的常见工作:

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

答案 1 :(得分:2)

这是你想要的吗?

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