调用内的一个异步函数在JavaScript中循环

调用内的一个异步函数在JavaScript中循环

问题描述:

我有以下的code:

for(var i = 0; i < list.length; i++){
    mc_cli.get(list[i], function(err, response) {
        do_something(i);
    });
}

mc_cli 是一个memcached的数据库的连接。你可以想像,回调函数是异步的,因此,它可能会在for循环已经结束执行。此外,在这种方式致电时 do_something(我)它总是使用的最后一个值的循环。

mc_cli is a connection to a memcached database. As you can imagine, the callback function is asynchronous, thus it may be executed when the for loop already ended. Also, when calling in this way do_something(i) it always uses the last value of the for loop.

我用封闭试图用这种方法

I tried with a closure in this way

do_something((function(x){return x})(i)) 

但显然这是再次使用始终for循环索引的最后一个值。

but apparently this is again using always the last value of the index of the for loop.

我也试过之前声明函数像这样循环:

I also tried declaring a function before the for loop like so:

var create_closure = function(i) {
    return function() {
        return i;
    }
}

,然后调用

do_something(create_closure(i)())

但同样没有成功,返回值总是被for循环的最后一个值。

but again without success, with the return value always being the last value of the for loop.

谁能告诉我我在带密封盖做错了吗?我想我理解他们,但我不明白为什么这是行不通的。

Can anybody tell me what am I doing wrong with closures? I thought I understood them but I can't figure why this is not working.

既然你通过一个阵列上运行,你可以简单地使用的forEach 它提供了列表项,和在回调的索引。迭代都会有自己的范围。

Since you're running through an array, you can simply use forEach which provides the list item, and the index in the callback. Iteration will have its own scope.

list.forEach(function(listItem, index){
  mc_cli.get(listItem, function(err, response) {
    do_something(index);
  });
});