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?
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.
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.
Arrow functions can never have duplicate named parameters, whether in strict or non-strict mode.
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);
More of less you can do it the same way
const getCountries = (data, callback) => {
//After ajax success
callback(response);
}
getCountries("data", ()=>{});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With