Passing parameters to a callback function using arrow function

烂漫一生 提交于 2021-02-08 12:37:13

问题


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?


回答1:


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);



回答2:


More of less you can do it the same way

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

getCountries("data", ()=>{});



回答3:


There is a way using the defaultValue, but I don't think it's the best.

If I can find a better way, I'll update the answer.

fetchItems = (callback) => {
  var response = {data: 'a'};  
  //After ajax success
  	
    callback(response);
}

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


来源:https://stackoverflow.com/questions/51190305/passing-parameters-to-a-callback-function-using-arrow-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!