4

I have a test_func that needs to be executed sequentially, ie; first_call, second_call, third_call.

Current output:-

started == first_call
VM81:49 status in : first_call  pending
VM81:47 started == second_Call
VM81:47 started == third_Call
VM81:49 status in : second_Call  pending
VM81:49 status in : third_Call  pending


function test_func(call_from){
  var deferred = $.Deferred();
    console.log('started ==',call_from)
  setTimeout(function(){
    console.log("status in :",call_from + '  ' +  deferred.state());
    deferred.resolve();
  },5000);

  return deferred.promise();
};
test_func('first_call').then(function(){
    test_func('second_Call')
  }).then(function(){
    test_func('third_Call')
  })

https://jsfiddle.net/44Lm3at0/

user1050619
  • 19,822
  • 85
  • 237
  • 413
  • possibly here can be your answer http://stackoverflow.com/questions/29880715/how-to-synchronize-a-sequence-of-promises – Kasia Jan 24 '17 at 21:45
  • 5
    Possible duplicate of [Resolve promises one after another (i.e. in sequence)?](http://stackoverflow.com/questions/24586110/resolve-promises-one-after-another-i-e-in-sequence) – Heretic Monkey Jan 24 '17 at 21:45
  • 1
    The first `.then` callback needs to be `return test_func('second_Call')` – 4castle Jan 24 '17 at 21:48
  • May I also suggest async? It's a library that offers a lot of functions helping you with control flow and other challenges that come with async programming. – newBee Jan 24 '17 at 22:04
  • Convert Promises to callbacks @newBee ? – Cameron Jan 24 '17 at 22:40
  • Async works with callbacks, true. This was just a general hint however. – newBee Jan 25 '17 at 06:05

1 Answers1

6

Make sure you send each Promise downstream in the Promise chain with return, like:

test_func('first_call')
  .then(function(){
    return test_func('second_Call');
  })
  .then(function(){
    return test_func('third_Call');
  })
  .then(function() {
     console.log('done');
   });

And see updated js fiddle to prove it: https://jsfiddle.net/44Lm3at0/1/

To add on, if you don't return the Promise, each item in the chain will run in parallel (offset by a little bit of time) instead of sequentially. By returning them, you inform JavaScript that you want to "wait" for the Promise to complete, allowing the chain of the then to work properly.

Cameron
  • 1,524
  • 11
  • 21