Keep a promise one at a time

I have test_func that needs to be executed sequentially, i.e. 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/

+4
source share
1 answer

Make sure you send each Promisedownstream in the chain Promiseusing return, for example:

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

And look at the updated js script to prove it: https://jsfiddle.net/44Lm3at0/1/

, return Promise, ( ) . , JavaScript, "" Promise, then .

+5

Source: https://habr.com/ru/post/1667693/


All Articles