7

I want to push functions with params to an array without getting them executed. Here is what i have tried so far:

 var load_helpers = require('../helpers/agentHelper/loadFunctions.js');
 var load_functions = [];
 load_functions.push(load_helpers.loadAgentListings(callback , agent_ids));
 load_functions.push(load_helpers.loadAgentCount(callback , agent_data));

But in this way functions gets executed while pushing. This Question provides similar example but without params. How can I include params in this example?

Community
  • 1
  • 1
Sohaib Farooqi
  • 5,457
  • 4
  • 31
  • 43
  • Are you bound to the array structure? Else I'd suggest a solution with an object containing references to the function and the arguments. – Marc Dix May 30 '16 at 08:05
  • Yes I need to pass this array to `async.parallel([] , callback());` There might be a workaround with object. – Sohaib Farooqi May 30 '16 at 09:17

3 Answers3

3

You have to bind the parameters to the function. The first parameter is the 'thisArg'.

function MyFunction(param1, param2){
   console.log('Param1:', param1, 'Param2:', param2)
}

var load_functions = [];
load_functions.push(MyFunction.bind(undefined, 1, 2));
load_functions[0](); // Param1: 1 Param2: 2
KMathmann
  • 444
  • 3
  • 15
  • 2
    No, you don't **have to** bind the parameters, although that's one approach. It's more readable and idiomatic with arrow functions to write `() => Myfunction(1, 2)`. –  Jun 04 '16 at 06:41
1

Push functions which do what you want:

load_functions.push(
  () => load_helpers.loadAgentListings(callback, agent_ids),      
  () => load_helpers.loadAgentCount   (callback, agent_data)
);
1

You can wrap added elements with function like that, let's mock load_helpers

var load_helpers = {
  loadAgentListings: function(fn, args) {
    args.forEach(fn)
  }
}

And try to use it in that way:

var a = []

a.push(function() {
  return load_helpers.loadAgentListings(function(r) {
    console.log(r)
  }, ['a', 'b', 'c'])
})

a[0]() // just execution

All depends on what level you want to pass additional arguments, second proof of concept

var a = []

a.push(function(args) {
  return load_helpers.loadAgentListings(function(r) {
    console.log(r)
  }, args)
})

a[0](['a', 'b', 'c']) // execution with arguments

With the bindings:

var a = []

a.push(load_helpers.loadAgentListings.bind(null, (function(r) {return r * 2})))

console.log(a[0]([1, 2, 3])) // execution with additional parameters
Krzysztof Safjanowski
  • 7,292
  • 3
  • 35
  • 47