Nested jQuery $.when

雨燕双飞 提交于 2019-12-04 11:52:09

问题


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("complete");
}); 

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.net/Z7fzR/


回答1:


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

http://jsfiddle.net/Z7fzR/1/




回答2:


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("complete");
});  

http://jsfiddle.net/Z7fzR/2/



来源:https://stackoverflow.com/questions/13843286/nested-jquery-when

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!