循环一个JavaScript里面异步进程 [英] Asynchronous Process inside a javascript for loop
问题描述
我运行以下形式的事件循环:
I am running an event loop of the following form:
var i;
var j = 10;
for (i = 0; i < j; i++) {
asycronouseProcess(callBackFunction() {
alert(i);
});
}
我想这显示是一系列经过10警报,显示数字0的问题是,由当时的回调函数被触发循环经历了几次迭代已经走了,它显示的更高的价值一世。关于如何解决此问题的任何建议?
What I would like this to display is a series of alerts showing numbers 0 through 10. The problem is that by the time the call back function is triggered the loop has already gone through a few iterations and it displays a higher value of i. Any recommendation on how to fix this?
推荐答案
您必须通过它传递给函数的地方,冻结 I
的值,所以它的值唯一存在用于在功能闭合循环的每次迭代。否则,所有的非同步回调只会看到 i的值
在循环是,当他们执行它们的回调(有时后,当循环完成它的价值到底),而不是每个自身的价值。
You have to freeze the value of i
by passing it into a function somewhere so it's value exists uniquely for each iteration of the loop in a function closure. Otherwise, all asynch callbacks will just see the value of i
at the end of the loop which is the value it has when they execute their callbacks (sometime later when the loop has finished), not each their own value.
假如你不能改变异步回调函数,那么你可以用这样的自我执行的功能,这对于每次循环创造了一个独特的功能封做到这一点:
Assuming you can't change the asynchronous function callback, then you could do it with a self executing function like this which creates a unique function closure for each iteration of the loop:
var i;
var j = 10;
for (i = 0; i < j; i++) {
(function(cntr) {
// here the value of i was passed into as the argument cntr
// and will be captured in this function closure so each
// iteration of the loop can have it's own value
asycronouseProcess(function() {
alert(cntr);
});
})(i);
}
如果您可以修改 asycronouseProcess()
函数,那么你可以只通过在那里的价值,并有 asycronouseProcess()
功能CNTR回这样的回调:
If you can modify the asycronouseProcess()
function, then you could just pass the value in there and have the asycronouseProcess()
function the cntr back to the callback like this:
var i;
var j = 10;
for (i = 0; i < j; i++) {
asycronouseProcess(i, function(cntr) {
alert(cntr);
});
}
这篇关于循环一个JavaScript里面异步进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!