I have the following situation:
var foo = [ 0, 1, 2 ]
for (var i in foo) {
Asyncstuff.get(URI).on(\'response\', function(res) { console.log(i); } });
}
<
Using recursive pattern loop with node.js
please refer my answer , am sure you can use this to solve your problem as you have the control over for loop
You need a closure. There are better ways than this, but this should clearly demonstrate the concept:
var foo = [ 0, 1, 2 ]
for (var i in foo) {
(function(i){
Asyncstuff.get(URI).on('response', function(res) { console.log(i); } });
})(i);
}
As cwolves has mentioned you need to wrap it using closure. The reason for that is in JavaScript and some other languages (ex: C#) closure capture "variables" and not "values" hence in your code the variable "i" is captured by the inner function and when that function executes it uses the captured variable "i" which obviously will be last value in the loop as the loop ends. You need to be careful when you use closures in languages such as JavaScript which captures variables.
In cwolves solution the "i" inside the function becomes a new variable and is not same as the I in the for loop and hence it works fine.