Reputation: 54949
How do I apply the same arguments to an array of functions?
Works:
async.parallel([func(arg, arg2), func2(arg, arg2)],
function() {
next();
});
The array has indeterminate / various functions functions inside though, so I'm not sure which functions I should be sending to the parallel method.
In various files I'm building the functions array:
funcArray.push(func2)
As a result I have an array like this:
[func, func2]
I would like to just do:
async.parallel(funcArray,
function() {
next();
});
and have all the same arguments be applied to all the functions. How can I do this? Thanks.
Ended up writing my own:
_.each(obj, function (func) {
func(req, res, function () {
i++
if (i == objSize) {
next()
}
})
})
Upvotes: 1
Views: 2401
Reputation: 106027
Untested, but this ought to work:
var args = [ arg, arg2 ]
, funcCalls = []
;
for(var i = 0; i < funcArray.length; i++) {
funcCalls.push(function() {
funcArray[i].apply(this, args); }
);
}
async.parallel(funcCalls, next);
Or, if you already know how many arguments you'll have, you don't need to use apply
in the middle section:
for(var i = 0; i < funcArray.length; i++) {
funcCalls.push(function() {
funcArray[i](arg, arg2); }
);
}
And finally you could really tighten it up with a map function as provided by e.g. Underscore.js:
async.parallel(_.map(funcArray,
function(func) { return function() { func(arg, arg2); } }
), next);
...but then the next guy who comes across your code might kill you.
Upvotes: 2