The easiest way is to use a closure. Whenever you have something asynchronous in a loop, it is the same thing.
for (var i .....) {
asynchronousFunction(function() {
use(i);
}
}
In this pseudocode snippet, the inner function captures the storage location referenced by i
. The loop runs, the i
increments to its final value, and then the async callbacks start getting called, all of them looking up the exact same location (not value).
The general solution is this:
for (var i .....) {
(function (i) {
asynchronousFunction(function() {
use(i);
});
})(i);
}
i.e. wrap the whole contents of your loop in an self-executing function.
Here, the value of outer i
gets passed into the wrapping self-executing anonymous function; this unique value's location gets captured by the async callback. In this way, each async gets its own value, determined at the moment the self-executing function is invoked.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…