最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Node.js同步请求超级请求中的同步请求

运维笔记admin15浏览0评论

Node.js同步请求超级请求中的同步请求

Node.js同步请求超级请求中的同步请求

如果我需要按顺序调用3个http API,那么对于以下代码来说,这将是一个更好的替代方法:

http.get({ host: 'www.example', path: '/api_1.php' }, function(res) { 
  res.on('data', function(d) { 

    http.get({ host: 'www.example', path: '/api_2.php' }, function(res) { 
      res.on('data', function(d) { 

        http.get({ host: 'www.example', path: '/api_3.php' }, function(res) { 
          res.on('data', function(d) { 


          });
        });
        }
      });
    });
    }
  });
});
}
回答如下:

使用像Futures这样的延迟。

var sequence = Futures.sequence();

sequence
  .then(function(next) {
     http.get({}, next);
  })
  .then(function(next, res) {
     res.on("data", next);
  })
  .then(function(next, d) {
     http.get({}, next);
  })
  .then(function(next, res) {
    ...
  })

如果你需要通过范围,那么就做这样的事情

  .then(function(next, d) {
    http.get({}, function(res) {
      next(res, d);
    });
  })
  .then(function(next, res, d) { })
    ...
  })
发布评论

评论列表(0)

  1. 暂无评论