无法从响应的结束事件中对 Http.Request 进行递归调用

Can't make recursive call to Http.Request from within end event of Response

本文关键字:Request Http 调用 递归 响应 事件 结束      更新时间:2023-09-26

我想发出一个HTTP GET请求,然后在最后一个请求完成后立即触发另一个请求。每个请求都接近相同(路径的小更改)。

我无法理解为什么以下内容不起作用(简化版本):

var options = { ... } // host, port etc
var req = request(options, function(res) {
  res.on('data', function(chunk) {
    data+=chunk;
  });
  res.on('end', function() {
    db.insert(data);
    options.path = somewhat_new_path;
    req.end(); // doesn't do anything
  });
});
req.end();

我知道有很多库等用于对异步代码进行排序,但我真的很想了解为什么我不能以这种方式实现异步循环。

>req.end()完成请求。在您完成请求之前,响应不会开始出现。因此,res.on('end',function(){})内部的req.end()没有任何意义。

如果你想用其他路径发出另一个请求,你可以做如下的事情:

var http = require('http');
var options = { ... } // host, port etc
makeRequest(options, function() {
  db.insert(data);
  options.path = somewhat_new_path;
  makeRequest(options, function() { //this will make a recursive synchronous call
    db.insert(data);
  });
});
options.path = another_path;
makeRequest(options, function() {  //this will make a asynchronous call
  db.insert(data);
});
var makeRequest = function(options, callback) {
  http.request(options, function(res) {
    res.on('data', function(chunk) {
      data+=chunk;
    });
    res.on('end', callback);
  }).end();
}