简体   繁体   中英

add a parameter to a callback function

if you run the code snippet below you will notice that the param value is undefined. in the final function despite adding it. is there a way to add the parameter and have it show up in the success function. is there a way to add parameters to a callback function? edit.. to avoid some confusion the parameter is not available until sendPersonDetailsToServer

  function saveSuccess(param) { console.log('save success'); console.log(param); } function sendPersonDetailsToServer(successCallback) { console.log('send person details to server'); successCallback('myParameter'); } function saveFiles(successCallback) { console.log('save Files'); successCallback(); } $(document).ready(function() { sendPersonDetailsToServer(function () { saveFiles(saveSuccess); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

You are not accepting the callback response parameter in sendPersonDetailsToServer callback method and also not passing it to saveSuccess method, thus getting undefined .

//Accept callback response parameter 
sendPersonDetailsToServer(function(response) {
  saveFiles(function() {
    //Pass it to saveSuccess
    saveSuccess(response);
  });
});

 function saveSuccess(param) { console.log('save success'); console.log(param); } function sendPersonDetailsToServer(successCallback) { console.log('send person details to server'); successCallback('myParameter'); } function saveFiles(successCallback) { console.log('save Files'); successCallback(); } $(document).ready(function() { //Accept callback response sendPersonDetailsToServer(function(response) { saveFiles(function() { //Pass it to saveSuccess saveSuccess(response); }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

The problem here is that your parm is not passed through the correct function. I've moved the param to the function saveFiles and it worked as expected

  function saveSuccess(param) { console.log('save success'); console.log(param); } function sendPersonDetailsToServer(successCallback) { console.log('send person details to server'); successCallback('myParameter'); } function saveFiles(successCallback) { console.log('save Files'); successCallback('myParameter'); // this is where your parameter should be passed } $(document).ready(function() { sendPersonDetailsToServer(function () { saveFiles(saveSuccess); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

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