【问题标题】:conditionally executing a callback有条件地执行回调
【发布时间】:2013-02-03 10:49:09
【问题描述】:

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

  1. 如果someData 等于某个值/通过某些条件测试,我只想调用getSomeOtherData

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

【问题讨论】:

    标签: node.js asynchronous callback control-flow


    【解决方案1】:

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

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

    【讨论】:

      【解决方案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();
                  });
              });
          });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-25
        • 1970-01-01
        • 1970-01-01
        • 2011-10-24
        • 2013-12-27
        • 2017-02-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多