I'm using async with Node.js. It runs fine when I have a fixed number of functions to execute:
async.series([
function(cb) { ...one ... },
function(cb) { .. two ... },
], function(err, res) {
...done
});
But now I need to execute an arbitrary number of functions, depending on values in one array, and cannot figure how to pass the array elements:
var values = [1, 2, 3, ... ];
var calls = [];
for (var i = 0; i < values.length; i++) {
calls.push(function(cb) {
HOW TO PASS values[i] HERE?
});
}
async.series(calls, function(err, res) {
...done
});
That's just the common async-in-a-loop problem. You will need a closure for the value of i
, in which the pushed function expression is declared. This can either be done with an IEFE as your loop body, or even easier with .forEach()
or .map()
:
var calls = values.map(function closure(val, i) {
return function(cb) {
// use val and i here, which are bound to this execution of closure
};
});
You should be able to use a closure:
var values = [1, 2, 3, ... ];
var calls = [];
for (var i = 0; i < values.length; i++) {
calls.push((function(index) {
return function(cb) {
// use values[index] here
};
})(i));
}
async.series(calls, function(err, res) {
...done
});