jQuery Deferred not calling the resolve/done callbacks in order

后端 未结 2 1086
余生分开走
余生分开走 2020-12-07 01:30

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

相关标签:
2条回答
  • 2020-12-07 02:20

    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 讨论(0)
  • 2020-12-07 02:23

    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.

    0 讨论(0)
提交回复
热议问题