1

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?

Bergi
  • 572,313
  • 128
  • 898
  • 1,281
collo21
  • 95
  • 1
  • 10

1 Answers1

1

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>
Community
  • 1
  • 1
Mosh Feu
  • 26,720
  • 15
  • 83
  • 122
  • Don't forget to `return` the promise from the callback – Bergi Feb 24 '16 at 16:10
  • That every asynchronous function should return a promise to be useful. In your case, the `then` callback is missing the `return`, so you can't chain anything onto it. – Bergi Feb 24 '16 at 16:28
  • Oh wait, you're still using `pipe`?! Replace it with `then` immediately, it's been deprecated for years now! – Bergi Feb 24 '16 at 16:29
  • @Bergi I just followed by the question :) But I was updated my answer.. Thanks.. About your comment, I don't understand. Do you mean that I should add `return ??` after the line `secondFunction('OK')`? If so, what I need to return? – Mosh Feu Feb 25 '16 at 08:08
  • @collo21 My pleasure ;) Good luck. – Mosh Feu Feb 25 '16 at 08:08
  • @MoshFeu: No, *before* `secondFunction('OK')` - you should return the promise you're creating there – Bergi Feb 25 '16 at 15:56