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

jquery how to pass parameter to callback function into pipe

我有下面这个简单的例子:

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

结果: 参数 = 确定 2个 1个 我失去了功能之间的同步。 如何通过同步将参数传递给 secondFunction 到管道中?

嗯,你需要做一些小改动:

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.

阅读完整答案:Javascript callback function with parameters

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>