【问题标题】:Execute promise one by one一一执行promise
【发布时间】:2017-06-09 22:03:22
【问题描述】:

我有一个 test_func 需要按顺序执行,即; first_call、second_call、third_call。

当前输出:-

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/

【问题讨论】:

标签: javascript jquery


【解决方案1】:

确保将Promise 链中的每个Promise 都发送到return 下游,例如:

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

并查看更新的 js fiddle 来证明这一点: https://jsfiddle.net/44Lm3at0/1/

补充一点,如果你不returnPromise,链中的每个项目将并行运行(偏移一点时间)而不是顺序运行。通过返回它们,您通知 JavaScript 您想要“等待”Promise 完成,从而使 then 的链正常工作。

【讨论】:

    猜你喜欢
    • 2017-08-11
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多