简体   繁体   中英

Callback function with optional second parameter

I have two functions which I send as callback function to the mapFunction method.

The problem is that the mapFunction method return callback with only one parameters declared inside of the function, and in both callbacks it has to be the first one.

func1(param) {...}
func2(param1, param2) {...}

mapFunction(list, callback) {
 //....
 const something = 'blabla';
 // if callback has second param run callback(something, secondParam)
 return callback(something) 
}

mapFunction(list, func1);
mapFunction(list, func2); // send second param

**How do I send second parameter with the callback function and call function with two parameters if two exists, if not call just with the one definer inside the scope of the mapFunction. Is it possible ? **

You can use Function.length

 function func1(param) { alert(param); } function func2(param1, param2) { alert(param1 + ' ' + param2); } function mapFunction(list, callback) { const something = 'blabla'; console.log(callback.length); return callback.length == 2 ? callback(something, list) : callback(something); } let list = 'secondParam'; mapFunction(list, func1); mapFunction(list, func2); 

JavaScript enables you to pass more arguments to a function than declared in its definition. So you can always pass two parameters to your callback and simply ignore the second parameter in func1

If I understand correctly, this code will help you. The first of values that must pass to func 1-3 is common between them and will pass from mapFunction, but other parameters will provide from where?? If you need pass them when calling mapFunc , you can try this stylish way that works fine with any other functions and any number of parameters (func4, ...):

  function func1(p1) { console.log(p1); } function func2(p1, p2) { console.log(p1 + ", " + p2); } function func3(p1, p2, p3) { console.log(p1 + ", " + p2 + ", " + p3); } function mapFunction(list, callback) { const something = 'insideValue'; return callback.apply(callback, [something].concat(Array.apply(null, arguments).slice(2, 1+callback.length)));// you can remove 1+callback.length and pass all parameters to callback but ignore extra parameters there (in func1-3). } var list=["any thing ..."]; mapFunction(list, func1); mapFunction(list, func2, "param2val"); mapFunction(list, func3, "param2val", "p3val"); 

Also you could have passed them as simple objects or array to the mapFunc as only one parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM