anil
anil

Reputation: 863

How to pass Array of Js functions to another Js function?

I am newbie to java script. I am writing some asynchronous functions let's say func1, func2, func3. But they have to execute one after another. So i decided to use async lib to execute one after another.

SCRIPT FILE:

 function func1(param1,param2){
  //dosomething ..
 }
 function func2(param3,param4){
  //dosomething ..
 }
 function func3(param5,param6){
  //dosomething ..
 }
 function myfunction(arr){
   console.log(arr);
   async.series(arr,function(){
      //do something ..
 });
 }

HTML FILE:

<a onclick="myfunction([func1('p1','p2'),func2('p3','p4'),func('p5','p6')])"></a>

But when i try console.log, it is giving null,null,null

kindly provide me some solution regarding.

Upvotes: 3

Views: 77

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074485

You're not passing an array of function references, you're passing an array of the result of calling those functions. The array will contain whatever those functions returned (or undefined if they don't return anything).

If you want to create a function reference with arguments "baked in", you can do that with Function#bind:

myFunction([func1.bind(null, 'p1','p2'), ...])
//               ^^^^^^^^^^^^         ^

Function#bind creates a new function that, when called, will call the original with a given this value (I've used null above on the assumption this isn't important) and the arguments you give bind (followed by any arguments the new function is called with).

Example:

myfunction([
  func1.bind(null, 'p1', 'p2'),
  func1.bind(null, 'p3', 'p4'),
  func1.bind(null, 'p5', 'p6')
]);
function func1(arg1, arg2) {
  console.log("func1 got (" + arg1 + "," + arg2 + ")");
}
function myfunction(functions) {
  functions.forEach(function(f) {
    f();
  });
}

Upvotes: 7

Related Questions