向回调函数添加参数

时间:2018-08-28 12:44:55

标签: javascript

如果运行下面的代码片段,您将注意到param值是未定义的。在最终功能中添加了它。有没有一种方法可以添加参数并将其显示在成功函数中。有没有一种方法可以将参数添加到回调函数?编辑..以避免混淆,直到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>

2 个答案:

答案 0 :(得分:3)

您不接受sendPersonDetailsToServer回调方法中的回调响应参数,也不将其传递给saveSuccess方法,从而得到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>

答案 1 :(得分:0)

这里的问题是您的parm没有通过正确的函数传递。我已经将参数移到函数saveFiles上,并且按预期工作

 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>