简体   繁体   English

jQuery如何将参数传递给回调函数到管道

[英]jquery how to pass parameter to callback function into pipe

I have the simple example below : 我有下面的简单示例:

function firstFunction(){
  var d = jQuery.Deferred();
  // some very time consuming asynchronous code...
  setTimeout(function() {
    console.log('1');
    d.resolve();
  }, 1000);
  return d.promise();
}
function secondFunction(param){
  console.log('parm = '+param);
  var d = $.Deferred();
  setTimeout(function() {
    console.log('2');
    d.resolve();
  }, 10);
  return d.promise();
}

firstFunction().pipe(secondFunction('OK'));

Resulat : param = OK 2 1 I lose the sync between functions. 结果:param = OK 2 1我失去了功能之间的同步。 How t can pass parameter to secondFunction into pipe with sync? t如何通过同步将参数传递给secondFunction到管道中?

Well, you need to do small change: 好吧,您需要做一些零钱:

Your code will execute secondFunction immediately and pass the return value from executing it as the argument to firstFunction which is unlikely what you want. 您的代码将立即执行secondFunction ,并将执行它的返回值作为参数传递给firstFunction ,这不太可能是您想要的。

Read the full answer: Javascript callback function with parameters 阅读完整答案: 带参数的Javascript回调函数

 console.log = function(message) { $('body').append('<div>' + message + '</div>'); } function firstFunction(){ var d = jQuery.Deferred(); // some very time consuming asynchronous code... setTimeout(function() { console.log('1'); d.resolve(); }, 1000); return d.promise(); } function secondFunction(param){ console.log('parm = '+param); var d = $.Deferred(); setTimeout(function() { console.log('2'); d.resolve(); }, 10); return d.promise(); } firstFunction().then(function() { secondFunction('OK') }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM