Monday, June 3, 2024
139
rated 0 times [  140] [ 1]  / answers: 1 / hits: 79761  / 12 Years ago, mon, november 12, 2012, 12:00:00

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.


More From » asynchronous

 Answers
54

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

[#82043] Saturday, November 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marinal

Total Points: 655
Total Questions: 99
Total Answers: 99

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;