0

I have an object with the following form.

sortedFilters:
  {
    task:{...},
    appointment:{...},
    email:{...}
  }

Now i want to use a for-in loop, to build my tasks array for async.parallel, which contains the functions to be executed asynchronously:

var tasks = [];
for (var entity in sortedFilters) {
  tasks.push(function(callback) {
    var entityResult = fetchRecordsForEntity(entity, businessUnits, sortedFilters);
    var formattedEntityResults = formatResults(entity, entityResult);  
    callback(null, formattedEntityResults);
  });
}

The problem is, that at the moment the functions are called, entity points at the last value of the loop (in this case it would be email).

How can i nail the exact value at the moment the function is added to the array?

Golo Roden
  • 140,679
  • 96
  • 298
  • 425
  • Can you please elaborate a little bit more which functions you are talking about in the end, and in how far `sortedFilters` is enumerable by a `for…in` loop? Especially I don't get the connection between your sample and the `async.parallel` call. Where and how does this happen? – Golo Roden Nov 26 '13 at 15:02

1 Answers1

0

You need to create a scope for the variable:

var tasks = [];
for (var en in sortedFilters) {
  (function(entity) {
     tasks.push(function(callback) {
        var entityResult = fetchRecordsForEntity(entity, businessUnits, sortedFilters);
        var formattedEntityResults = formatResults(entity, entityResult);  
        callback(null, formattedEntityResults);
     });
  })(en);
}
qwertynl
  • 3,912
  • 1
  • 21
  • 43