调用内的一个异步函数在JavaScript中循环 [英] Calling an asynchronous function within a for loop in JavaScript

查看:109
本文介绍了调用内的一个异步函数在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);
  });
});

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆