When using callbacks inside a loop in javascript, is there any way to save a variable that’s updated in the loop for use in the callback? [duplicate]

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

Leave a Comment