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
?
@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.