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.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…