最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Nested jQuery $.when - Stack Overflow

programmeradmin4浏览0评论

Essentially I am tring to write this:

var async1 = $.when( a1() ).then(function(){ a2() });
var async2 = $.when( a3() ).then(function(){ a4() });

$.when(async1, async2).then(function(){ 
    console.log("plete");
}); 

But at the moment when a1 and a3 have executed the function considers itself resolved.

I put together the same example in a fiddle: /

Essentially I am tring to write this:

var async1 = $.when( a1() ).then(function(){ a2() });
var async2 = $.when( a3() ).then(function(){ a4() });

$.when(async1, async2).then(function(){ 
    console.log("plete");
}); 

But at the moment when a1 and a3 have executed the function considers itself resolved.

I put together the same example in a fiddle: http://jsfiddle/Z7fzR/

Share Improve this question asked Dec 12, 2012 at 15:40 Jon WellsJon Wells 4,2599 gold badges41 silver badges69 bronze badges 4
  • When do you expect them to be resolved? – Explosion Pills Commented Dec 12, 2012 at 15:42
  • @ExplosionPills when a1, a2 a3 and a4 are all resolved I would expect the final when to be resolved. If you follow? – Jon Wells Commented Dec 12, 2012 at 15:43
  • Just guessing... What would happen if you changed it to this? $.when( a1().then(function(){ a2() })); – chrisfrancis27 Commented Dec 12, 2012 at 15:48
  • @ChrisFrancis that did work but ExplosionPills has nailed it – Jon Wells Commented Dec 12, 2012 at 15:55
Add a ment  | 

2 Answers 2

Reset to default 11

You never actually return the promise objects created by a2() and a4() from the callback; this effectively returns null, which apparently counts as a pletion for $.when purposes:

http://jsfiddle/Z7fzR/1/

You are throwing away the promise objects that a2 and a4 return, essentially passing undefined back to the original when, which causes it to resolve immediately:

If a single argument is passed to jQuery.when and it is not a Deferred, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.

Add some returns and it works fine.

var async1 = $.when(a1()).then(function(){ return a2(); });
var async2 = $.when(a3()).then(function(){ return a4(); });

$.when(async1, async2).then(function(){
    console.log("plete");
});  

http://jsfiddle/Z7fzR/2/

发布评论

评论列表(0)

  1. 暂无评论