在JavaScript中的for循环中调用异步函数
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);
});
});
更多相关文章
- JavaScript声明全局变量三种方式的异同
- 【Python】【matplotlib】面向对象方式绘图
- 【项目实战】自监控-09-DataFrame索引操作(上篇)
- 一个有意思的学习python的方式
- 以DAG方式调度作业
- caffe中各语言预处理对应方式
- 如何在DataFrame中找到重复的索引?
- Django rest framework 使用自定义认证方式
- 读取python中的unicode文件,该文件以与python源代码相同的方式声