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

javascript - jQuery Deferred not calling the resolvedone callbacks in order - Stack Overflow

programmeradmin1浏览0评论

Code example: /

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?

Code example: http://jsfiddle/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?

Share Improve this question edited Jun 4, 2011 at 14:30 lonesomeday 238k53 gold badges327 silver badges328 bronze badges asked Mar 1, 2011 at 19:25 Adam SilverAdam Silver 2502 silver badges6 bronze badges 2
  • 1 i think the problem is with the use of setTimeOut just changed the values and get the desired result jsfiddle/MhEPw/2 – Rafay Commented Mar 1, 2011 at 19:34
  • the OP didnt specifically mentioned about getting the desired seq regardless of time each fun() takes, it can be achieved by $.when(do1() ).then(fn(){ do2() } ); jsfiddle/MhEPw/3 ... may be i have misunderstood altogether – Rafay Commented Mar 1, 2011 at 19:52
Add a ment  | 

2 Answers 2

Reset to default 5

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/pVVad/

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

Adam, if you change your "setTimeout" by a "for" you can see that is executed in order, setTimeout adds a "trigger" to call "another action", this "another action" is executed in the time that you have specified, but the setTimeout calls is executed in order.

If you don't use setTimeout, your script will be executed in order.

发布评论

评论列表(0)

  1. 暂无评论