Masiar Masiar - 3 months ago 5
Javascript Question

Calling an asynchronous function within a for loop in JavaScript

I have the following code:

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

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
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


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.


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) {