Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to a callback function using arrow function

I know this is a duplicated question with ES5, but I am looking for the syntax with ES6 arrow function. My code below:

fetchItems = (callback) => {
    //After ajax success
    callback(response);
}

const myParams = {name:"John"}
this.fetchItems((res) => {
    console.log(res.data);
});

For the above scenario, I want to pass some parameters(myParams) along with the function call, how can I achieve that?

like image 992
Jaison James Avatar asked Jul 05 '18 11:07

Jaison James


People also ask

How do you pass parameters to a call back function?

function tryMe(param1, param2) { alert(param1 + " and " + param2); } function callbackTester(callback, someArg, AnotherArg) { callback(); } callbackTester(()=> tryMe("hello", "goodbye"), "someArg", "AnotherArg"); ...or simply if you dont have multiple arguments doing other stuff.

Can we pass arguments in callback function?

A callback function is a function that is passed as an argument to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed.

Can arrow functions have parameters?

Arrow functions can never have duplicate named parameters, whether in strict or non-strict mode.


2 Answers

You can do that:

const fetchItems = (callback, ...params) => {
    //Do whatever you want with the params
    callback(response);
}

Example of usage:

const fetchItems = (callback, ...params) => {
    callback(params);
}
    
fetchItems (console.log, 'foo', 1);
like image 190
Guerric P Avatar answered Oct 17 '22 05:10

Guerric P


More of less you can do it the same way

const getCountries = (data, callback) => {
    //After ajax success
    callback(response);
}

getCountries("data", ()=>{});
like image 4
void Avatar answered Oct 17 '22 04:10

void