0

Every time I want a function run with callback, I have to change my parameter from (par1,par2) to (args). Is there any way to keep my parameter name?

Here is my code now:

function runwithcallback(callback, ...args) {
  callback(args);
}

function Boo(args){
  let par1 = args[0];
  let par2 = args[1];
}
function Foo(args){
  let par1 = args[0];
  let par2 = args[1];
  let par3 = args[2];
}

//normal call
Boo(["1","2"]);
Foo(["1","2","3"]);

//call with callback
runwithcallback(Boo,"1","2");
runwithcallback(Foo,"1","2","3");

And what I want:

function runwithcallback(callback, ...args) {  
  callback(args);
}

function Boo(par1, par2){
} 
function Foo(par1, par2, par3){ 
}

//normal call
Boo("1","2");
Foo("1","2","3");

//call with callback
runwithcallback(Boo,"1","2"); 
runwithcallback(Foo,"1","2","3");
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Ming
  • 9
  • 4
    You can use [`.apply()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) or spread syntax. – Pointy Dec 06 '20 at 14:24
  • 3
    Spread the args into the callback: `callback(...args);` ? – Nick Parsons Dec 06 '20 at 14:24
  • 1
    Just a very subjective observation: instead of doing any of that I'd pass an actual callback function: `runwithcallback(() => Boo("1", "2", "3"));` –  Dec 06 '20 at 14:32
  • to @NickParsons I succeed by using `callback(...args);`. Thanks, can you use formal answer to let me select you to best answer? @ChrisG yes,I also use lambda with short function. – Ming Dec 06 '20 at 14:37

0 Answers0