Search code examples
node.jsasynccallback

How to count callbacks?


I tried collect data from 3 sources but these are async. Therefore i tried to count callback. This is code which i wrote for this purpose.

var http = require('http');
var data_str1 = '';
var data_str2 = '';
var data_str3 = '';
var ended = 0;
function callback1(response){
    response.on('end', function(){ended++;});
    response.on('data', function(data){
        data_str1 += data;
    });
}

function callback2(response){
    response.on('end', function(){ended++;});
    response.on('data', function(data){
        data_str2 += data;
    });
}

function callback3(response){
    response.on('end', function(){ended++;});
    response.on('data', function(data){
        data_str3 += data;
    });
}

http.get(process.argv[2], function(response){
    callback1(response);
    if (ended == 3) console.log(data_str1);
});

http.get(process.argv[3], function(response){
    callback2(response);
    if (ended == 3) console.log(data_str2);
});

http.get(process.argv[4], function(response){
    callback3(response);
    if (ended == 3) console.log(data_str3);
});

Can you tell me what is the problem in this code?


Solution

  • Here's my solution. I've tested and it works.

    var http = require('http');
    var concat = require('concat-stream');
    
    var urls = [];
    var responses = [];
    var count = 0;
    
    for (var i = 2; i < process.argv.length; i++) {
      urls.push(process.argv[i]);
    }
    
    function readResponse(index) {
      http.get(urls[index], function(response) {
        response.pipe(concat(function(data) {
          responses[index] = data.toString();
          count++;
    
          if (count == 3) {
            responses.forEach(function(response) {console.log(response);});
          }
        }));
      });
    }
    
    for (var i = 0; i < urls.length; i++) {
      readResponse(i);
    }