I have the following code:

我有以下代码:

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

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.

mc_cli是与memcached数据库的连接。可以想象,回调函数是异步的,因此可以在for循环结束时执行。此外,当以这种方式调用do_something(i)它总是使用for循环的最后一个值。

I tried with a closure in this way

我用这种方式尝试了一个闭包

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

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:

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

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

and then calling

然后打电话

do_something(create_closure(i)())

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

但是再次没有成功,返回值始终是for循环的最后一个值。

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.

任何人都可以告诉我我的闭包装有什么问题吗?我以为我理解了他们,但我无法理解为什么这不起作用。

8 个解决方案

#1


73

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.

由于您正在运行数组,因此您可以简单地使用提供列表项的forEach和回调中的索引。迭代将有自己的范围。

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

更多相关文章

  1. JavaScript声明全局变量三种方式的异同
  2. 【Python】【matplotlib】面向对象方式绘图
  3. 【项目实战】自监控-09-DataFrame索引操作(上篇)
  4. 一个有意思的学习python的方式
  5. 以DAG方式调度作业
  6. caffe中各语言预处理对应方式
  7. 如何在DataFrame中找到重复的索引?
  8. Django rest framework 使用自定义认证方式
  9. 读取python中的unicode文件,该文件以与python源代码相同的方式声

随机推荐

  1. 有关Xml.Serialization的文章推荐6篇
  2. 关于Spy的详细介绍
  3. 有关循环过程的文章推荐5篇
  4. 关于应用名称的文章推荐
  5. 用户列表的10篇内容推荐
  6. 关于OFBiz的详细介绍
  7. 有关UTF-16的问题及解决方法
  8. 关于结果保存的10篇文章推荐
  9. 布局文件如何使用?总结布局文件实例用法
  10. 关于XMLHTTP对象的详细介绍