Tuesday, May 28, 2024
 Popular · Latest · Hot · Upcoming
90
rated 0 times [  91] [ 1]  / answers: 1 / hits: 53829  / 13 Years ago, sat, august 13, 2011, 12:00:00

Let's say I have something as follows:



for(var i = 0; i < length; i++){
var variable = variables[i];
otherVariable.doSomething(variable, function(err){ //callback for when doSomething ends
do something else with variable;
}


By the time the callbacks are called, variable will inevitably be the last variable for all the callbacks, instead of being a different one for each callback, as I would like. I realize that I could pass variable to doSomething() and then get that passed back as part of the callback, but doSomething() is part of an external library, and I'd rather not mess around with the source code for that.



Do those of you that know JavaScript better than I do know if there are any alternative ways to do what I'd like to do?



Best, and thanks,
Sami


More From » callback

 Answers
7

A common, if ugly, way of dealing with this situation is to use another function that is immediately invoked to create a scope to hold the variable.



for(var i = 0; i < length; i++) {
var variable = variables[i];
otherVariable.doSomething(function(v) { return function(err) { /* something with v */ }; }(variable));
}


Notice that inside the immediately invoked function the callback that is being created, and returned, references the parameter to the function v and not the outside variable. To make this read much better I would suggest extracting the constructor of the callback as a named function.



function callbackFor(v) {
return function(err) { /* something with v */ };
}
for(var i = 0; i < length; i++) {
var variable = variables[i];
otherVariable.doSomething(callbackFor(variable));
}

[#90626] Friday, August 12, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
frederickmohamedw

Total Points: 21
Total Questions: 123
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
frederickmohamedw questions
Wed, Sep 23, 20, 00:00, 4 Years ago
Sat, Jul 18, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
Sat, Jan 11, 20, 00:00, 4 Years ago
Fri, Dec 27, 19, 00:00, 5 Years ago
;