使用延迟到多个ajax调用的链循环 [英] Using deferred to chain loops with multiple ajax calls
本文介绍了使用延迟到多个ajax调用的链循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有很多问题已经对此有了答案,但到目前为止所有这些都没有用到这种设置。
There are multiple questions that already have an answer about this, but all aren't working so far it this kind of setup.
function login(u,p) {
console.log(1);
return $.post(url, {u,p});
}
function out() {
console.log(3);
//a function that does not return deferred
// clear cookies
}
function doSomething() {
console.log(2);
// a function that returns a deferred
return $.post(...);
}
var data = [{u: 'au', p: 'ap'}, {u: 'bu', p: 'bp'}]
$.each(data, function(k,v){
login(v.u, v.p).then(doSomething).then(out);
});
我原以为它的序列如下:
I was expecting it's sequence to be like:
1
2
3
1
2
3
但是我得到了
1
2
1
3
2
3
为什么是这样的,即使我等待承诺使用解决,然后
Why is it like that, even though I am waiting for the promise to be resolve using then
推荐答案
这个想法是创建一个像@Popnoodles所提到的递归函数。
The idea is to create a recursive function like @Popnoodles have mentioned.
例如
function a() {
return $.post();
}
function b() {
return $.post();
}
function c() {
console.log('no promise.');
}
// and the recursive main function
function main() {
if(counter < data.length){
$.when(a().then(b).then(c)).done(function(){
counter++;
main();
});
}
}
main();
以下是它的工作原理,打开控制台,看看它是如何按顺序记录功能的。
Here is how it works, open the console to see how it logs the function in sequence.
这篇关于使用延迟到多个ajax调用的链循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文