5

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

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

  2. 在这两种情况下,我总是想打电话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();
           });
       });
   });
});           
4

2 回答 2

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();
    }
  });
}); 
于 2013-02-18T22:06:04.640 回答
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();
            });
        });
    });
});
于 2013-02-18T22:56:53.233 回答