Javascript 逐一履行承诺
我有一个测试函数需要按顺序执行,即;第一个电话,第二个电话,第三个电话 电流输出:-Javascript 逐一履行承诺,javascript,jquery,Javascript,Jquery,我有一个测试函数需要按顺序执行,即;第一个电话,第二个电话,第三个电话 电流输出:- 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 f
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')
})
确保将每个
承诺
与返回
一起发送到承诺链的下游,如:
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以证明这一点:
此外,如果您不返回承诺
,链中的每个项目将并行运行(抵消一点时间),而不是按顺序运行。通过返回它们,您通知JavaScript您希望“等待”完成承诺,从而允许然后的链正常工作。这里可能是您的答案第一个的可能重复。然后回调需要返回test\u func(“第二次调用”)
我可以建议异步吗?这是一个库,它提供了许多函数,帮助您解决异步编程带来的控制流和其他难题?