4

I got a dynamic asynchronous request (for the jsfiddle I used ajax) that I need to wait regardless of success or failure, which means I only need to know that all are processes are finished even if some request failed.

//Dynamic: In my case this is produced by an ajax request so the number of followup async request is flexible

So I originally used this code:

    $.when.apply($,deferreds).done(function() {
        $("div").append("<p>All done!</p>");
    }).fail(function(){
        $("div").append("<p>Something failed!</p>");
    });

But in the scenario that one of the deferred failed, the fail callback will be called immediately. I tried changing it to always() but the result is:

Uncaught TypeError: Object # has no method 'always'

So how can I implement an always() kind of solution for this?

Fiddle

My original source: jQuery Deferred - waiting for multiple AJAX requests to finish

Community
  • 1
  • 1
Marl
  • 1,492
  • 2
  • 22
  • 37

2 Answers2

9

If you just want to wait a list of $.Deferred to end regardless they are rejected or resolved, you have the solution in my answer in your original source jQuery Deferred - waiting for multiple AJAX requests to finish :

$.when.apply($, $.map(deferreds, function(d) {
    var wrapDeferred = $.Deferred();
    // you can add .done and .fail if you want to keep track of each results individualy
    d.always(function() { wrapDeferred.resolve(); });
    return wrapDeferred.promise();
}));
Community
  • 1
  • 1
Mordhak
  • 2,646
  • 2
  • 20
  • 14
  • Damn, the answer is already in the source. 0_0 I didn't saw that. Thanks for the answer. – Marl Feb 14 '13 at 10:39
  • Thank you so much for this, I'm not really a Javascript coder and this saved my life! Do you know how I can then work out which ones worked and which ones failed (and why)? – LaughingJohn Mar 11 '13 at 16:01
  • You are missing a closing parenthesis on the last line, should be })); – Chloraphil Aug 06 '13 at 20:20
0

Ok like what Kevin B suggested. I used a custom deferred that will be resolve no matter the outcome of the asynch request.

var deferreds = $.map(i, function (count, index){
    var waitingProcess = new $.Deferred(); //Here is the custom deferred
    if(count == 7) {
        $.Deferred().fail(function(){
            $("div").append("<p>Task #" + count + " failed.");
            waitingProcess.resolve(); //resolve it no matter the outcome
        }).reject();
    }else{
        $.post('/echo/html/', {
            html: "<p>Task #" + count + " complete.",
            delay: count
        }).success(function(data) {
            $("div").append(data);
            waitingProcess.resolve(); //resolve it no matter the outcome
        });
    }
    return waitingProcess.promise();
});

Fiddle

Community
  • 1
  • 1
Marl
  • 1,492
  • 2
  • 22
  • 37