Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Deferred - waiting for dynamic async requests to finish all even if some failed

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

like image 683
Marl Avatar asked Jan 14 '23 05:01

Marl


1 Answers

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();
}));
like image 80
Mordhak Avatar answered Jan 16 '23 22:01

Mordhak