简体   繁体   中英

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. How t can pass parameter to secondFunction into pipe with sync?

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.

Read the full answer: 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> 

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