问题描述
我花了太多时间寻找类似的问题和尝试解决方案,所以我希望有人有解决方案。
I've spent far too many hours searching for similar questions and trying solutions, so I hope someone has a solution.
基本上,我希望收到通知当函数a()完成时。问题是该函数包含一个ajax调用和一个调用b()的循环,它再次包含一个ajax调用。
Basically, I would like to be notified when a function a() has completed. The problem is that the function contains an ajax call and a loop that calls b(), which again contains an ajax call.
使用FIDDLE更新:
UPDATED WITH FIDDLE: http://jsfiddle.net/hsyj7/1/
如下所示:
// called by main()
function a() {
return $.ajax("http://url1").pipe(function(data){
for (var i = 0; i < 2; i++) {
console.log('a called');
b();
}
});
}
// called by a()
function b() {
for (var i = 0; i < 2; i++) {
$.ajax("http://url2", function(data){
// do something
console.log('b called');
}
}
}
function main(){
$.when(a()).done(function(){
console.log('all completed');
});
}
我想看到的是什么是,可能同时调用顶部的a():
What I would like to see then is, possibly with both calls to a() at the top:
a called
b called
b called
a called
b called
b called
all completed
相反,我得到
a called
all completed
b called
b called
或其中的一些变体。
我知道以上代码缺少循环和b()中的延迟功能。
在我尝试的一些变种中,main()中的done()处理程序永远不会被调用。
I am aware that the above code is missing defer functionality in both the loop and in b().In some of the variants I have tried, the done() handler in main() is never called.
任何人都知道怎么做?
推荐答案
是的,使用延期
是这样做的方法:
Yeah, using Deferred
is the way to do that:
function a() {
var def = $.Deferred();
$.ajax("http://url1").done(function(data){
var requests = [];
for (var i = 0; i < 2; i++) {
requests.push(b());
}
$.when.apply($, requests).then(function() { def.resolve(); });
});
return def.promise();
}
// called by a()
function b() {
var def = $.Deferred(),
requests = [];
for (var i = 0; i < 2; i++) {
requests.push($.ajax("http://url2").done(function(data){
// do something
console.log('b called');
});
}
$.when.apply($, requests).then(function() { def.resolve(); });
return def.promise();
}
function main(){
$.when(a()).done(function(){
console.log('all completed');
});
}
//编辑:用<$ c替换 .pipe
$ c> .done 。
// Replaced .pipe
with .done
.
这篇关于在循环中使用$ .Deferred()和嵌套的ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!