本文介绍了在 JavaScript 的 for 循环中调用异步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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(i) 时,它总是使用 for 循环的最后一个值.

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.

我尝试用这种方式关闭

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.

我也尝试在 for 循环之前声明一个函数,如下所示:

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);
  });
});

这篇关于在 JavaScript 的 for 循环中调用异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 03:21