0

I am trying to create multiple http requests in Node.js, with each of them receiving a separate response. What I want to do is to identify which event corresponds to which call:

for (var i=0; i<100; i++) {
    var req = http.request(options, function(response) {
        var str = "";

        response.on('data', function (chunk) {
            console.log(str.length);
        });

        response.on('end', function () {
            console.log("End of response");
        }); 

    }); 

    req.on('error', function(err) {
        console.log(err.message);
    });

    req.end();
}

Is there any way of properly identifying which response corresponds to each iteration? I am basically creating 100 response instances, but they all emit the same event, so the event emitting/handling is done globally. Basically, could I somehow tie i and the events emitted by response?

Anas
  • 5,622
  • 5
  • 39
  • 71
cgf
  • 3,369
  • 7
  • 45
  • 65
  • possible duplicate of [How do JavaScript closures work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) and [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Ben Fortune Aug 18 '14 at 15:18
  • Maybe you should be using something like the [Q Promise library](https://github.com/kriskowal/q/wiki/API-Reference) to attach handler behaviour to each request. It's not clear what you're trying to do here that's different for each request you've made. If you want to capture `i`: `var _i = i` should give you a "local" copy for each instance. – tadman Aug 18 '14 at 15:20

1 Answers1

0

@BenFortune was right, this was related to closures. The example in the original question was overly-simplified, but if you have a construction similar to:

for(var i=0; ... ) {

    function someFunction() {

    }

}

and you want to keep track of something external to the function inside the function, then you should look into closures.

cgf
  • 3,369
  • 7
  • 45
  • 65