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?

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

6 Comments

Don't forget to return the promise from the callback
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.
Oh wait, you're still using pipe?! Replace it with then immediately, it's been deprecated for years now!
@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?
@collo21 My pleasure ;) Good luck.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.