1

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

just use async.apply to add arguments to function. Refer to github.com/caolan/async#applyfunction-arguments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.