$.Deferred: How to detect when every promise has been executed

More sophisticated promise libraries have an allSettled() function like Q or Promise.settle like Bluebird.

In jQuery, you could implement such a function yourself as well and extend the $ namespace with it, but that will only be necessary if you need it often and performance-optimized.

A simpler solution would be to create a new promise for each of the ones you are waiting for, and fulfilling them even when the underlying one is rejected. Then you can use $.when() on them without problems. In short:

// using Underscore's .invoke() method:
$.when.apply(null, _.invoke(promises, "then", null, $.when)).done(…)

More stable:

$.when.apply($, $.map(promises, function(p) {
    return p.then(null, function() {
        return $.Deferred().resolveWith(this, arguments);
    });
})).then(…);

You might change the then callbacks a bit to distinguish between fulfilled and rejected results in the final done.

Leave a Comment