我有一个需要按顺序执行的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/
确保您发送链中的 每个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小提琴来证明它:https: //jsfiddle.net/44Lm3at0/1/
要添加上,如果你不这样做return
的Promise
,在链中的每个项目将在并行(由一点点时间偏移)上运行,而不是按顺序.通过返回它们,您通知JavaScript您要"等待" Promise
完成,允许链的then
正常工作.