When using callbacks inside a loop in javascript, is there a way to save a variable that is updated in a loop for use in a callback?

Let's say I have something like this:

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 callbacks, instead of being different for each callback as I would like. I understand that I could pass variable to doSomething() and then pass this as part of the callback, but doSomething() is part of an external library, and I would prefer not to interfere with the source code for this.

Do you have anyone who knows JavaScript better than I know, are there alternative ways to do what I would like to do?

Best and thanks
Themselves

+50
javascript callback
Aug 13 '11 at 23:32
source share
2 answers

A common, if not ugly, way to deal with this situation is to use another function that is called immediately to create an area 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)); } 

Note that inside the directly called function, the callback that is created and returned refers to the parameter on function v , and not on the external variable . To make this much better, I would suggest retrieving the callback constructor 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)); } 
+39
Aug 13 '11 at 23:40
source share

Well, it seemed to me that this is understandable. I needed to wrap function(var) around otherVariable.doSomething() , so the updated code looks like this:

 for(var i = 0; i < length; i++){ var variable = variables[i]; (function(var){ //start wrapper code otherVariable.doSomething(var, function(err){ //callback for when doSomething ends do something else with var; //please note that i'm dealing with var here, not variable } })(variable);//passing in variable to var here } 

hope this helps someone else who gets stuck in this in the future!

@ aparker42, I would still like to hear your answer to my question in the commentary on your question, as this still confuses me.

EDIT: of course, since this is javascript, you would not want to use var as the variable name.

+26
Aug 14 '11 at 17:05
source share



All Articles