Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

javascript - jQuery Deferred not calling the resolve/done callbacks in order

Code example: http://jsfiddle.net/MhEPw/1/

I have two jQuery Deferred objects.

I want to have more than one 'async' request happening - and after they all run I want the callbacks (the .done functions) to be run in order they were specified in. Unfortunately they don't run in order.

Maybe I am looking for some functionality here that Deferred doesn't provide?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you need to do is link all of your request with one master deferred object and register all of your callbacks on its promise. The master deferred object would need to listen to the individual requests and resolve accordingly. The simplest way to achieve this would be to define all of the deferred objects up front to avoid the chicken and egg problem:

var d1 = $.Deferred();
var d2 = $.Deferred();
var def = $.when(d1, d2);

def.done(function() {
    alert(1);
});
setTimeout(function() {
    d1.resolve();
}, 3000);

def.done(function() {
    alert(2);
});
setTimeout(function() {
    d2.resolve();
}, 1000);

Fiddle: http://jsfiddle.net/pVVad/

Changing the order of deferred objects definitions is possible but it would make the example much more complicated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...