使用延迟到多个ajax调用的链循环
16lz
2021-01-22
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
But I get
但我明白了
1
2
1
3
2
3
Why is it like that, even though I am waiting for the promise to be resolve using then
为什么会这样,即使我在等待使用当时的解决方案
2 个解决方案
#1
2
If you want the logins to run synchronously:
如果您希望登录同步运行:
var p = new jQuery.Deferred();
$.each(data, function(k,v){
p.then(function() {
return login(v.u, v.p);
}).then(doSomething).then(out);
});
Each new item iterated over in $.each
won't trigger a new response until p
finishes the last one.
在$ .each中迭代的每个新项目都不会触发新的响应,直到p完成最后一个。
更多相关文章
- 【问题解决方案】ImportError: No module named 'pygal'
- Python 黏包及黏包解决方案
- 无法安装ndg-httpsclient或者我的解决方案错误
- Linux无法连接网络解决方案
- Media-S 简介(一个开源的DRM解决方案)
- AppScan安全问题解决方案
- PLSQL乱码解决方案
- 数据库不支持中文解决方案(mysql)
- Mysql替代解决方案Cassandra