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?

2
  • Are you bound to the array structure? Else I'd suggest a solution with an object containing references to the function and the arguments. Commented May 30, 2016 at 8:05
  • Yes I need to pass this array to async.parallel([] , callback()); There might be a workaround with object. Commented May 30, 2016 at 9:17

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

1 Comment

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).
1

Push functions which do what you want:

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

Comments

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

Comments

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.