Calling an asynchronous function within a for loop in JavaScript

Masiar picture Masiar · Nov 12, 2012 · Viewed 65k times · Source

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.

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.

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

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.

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.

Answer

Joseph picture Joseph · Nov 12, 2012

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