How can execute a function after a number of ajax requests have all completed regardless of whether they succeeded or error-ed out?
I've been trying to use $.when.apply(this, array)
to pass an array of deferred jqXHR objects. However just like the docs say
In the multiple-Deferreds case where one of the Deferreds is rejected, jQuery.when immediately >fires the failCallbacks for its master Deferred. Note that some of the Deferreds may still be >unresolved at that point.
How can leverage jQuery deferred objects to always wait for all the ajax calls to finish?
Maybe I should create my own deferred that will wrap all the other deferreds? If so I'm not quite clear how to set that up.
In the spirit of how the Promise specification is likely going for the future with a
PromiseInspection
object, here's a jQuery add-on function that tells you when all promises are done, whether fulfilled or rejected:Then, you can use it like this:
Keep in mind that
$.settle()
will always fulfill (never reject) and the fulfilled value is an array ofPromiseInspection
objects and you can interrogate each one to see if it was fulfilled or rejected and then fetch the corresponding value or reason. See the demo below for example usage:Working demo: https://jsfiddle.net/jfriend00/y0gjs31r/