nodejs socket hang up error in nested callback

I try to put many callbacks in a callback, but the program will shut down after the return of several success requests and post "socket hang up" error. I try to collect data from response and output them at once, can someone tell me which part goes wrong... By the way, I hide the details of request method, I promise the request method works on http call.

http.request(options1,function(data){
    var condition=data.length;
    var result=[];
    data.foreach(item,function(data){
        http.request(options2, function(data){
             if(data) result.push(data);
             condition--;
             if(condition<=0) console.log(result);
        }
    });
});

for my http.request method

var request=function(options,callback){
    http.request(options,function(res){
        var body;

        res.on('data',function(chunk){
             body+=chunk;
        });
        res.on('end',function(){
             callback(JSON.parse(body));
        });

    request.end();
};

That's not the correct usage of http.request().

  • The http.request() callback is passed an IncomingMessage object, not buffered response data.

    • EDIT: Your custom request() should look something like this, although you should handle errors too. Note the proper placement of request.end() and initializing var body = '':

      function request(options, callback) {
        http.request(options,function(res) {
          var body = '';
          res.setEncoding('utf8');
          res.on('data',function(chunk) {
            body += chunk;
          }).on('end',function() {
            callback(JSON.parse(body));
          });
        }).end();
      }
      
  • You're missing .end() for your requests so that node.js knows you are ready to actually send the HTTP request: http.request(..., ....).end();. This is the cause of your particular error... the server hangs up the connection because it got tired of waiting for your request after the TCP connection was opened.