I have following code:
var i;
for (i = 1; i <= 10; i++) {
console.log(i);
}
This obviously prints numbers from 1 to 10 just fine. Then I want to do this asynchronously:
var i;
for (i = 1; i <= 10; i++) {
setImmediate(function() { console.log(i); });
}
And here it is — it prints only 11-s. First I was wondering if this is some shared state problem (it happened when I tried to fetch multiple pages with PhantomJS, and ended fetching the same one N times, so I've thought something is not quite async-safe there), then compacted the issue up to example shown above, then understood it's because javascript closures don't seem to capture their environment — so despite the fact I used i
in function, it uses actual value of i
at the moment of execution, which is, indeed, 11.
Unfortunately, due to design of API, I'm unable to pass additional parameters to callbacks to make i
local to function, as I can't change the signature.
So, question is — how to rewrite second example to work correctly?