Reputation: 2604
What would be the right way to handle an array of ajax responses? I mean, since it is an array of promises, what happens when one of those ajax calls fail?
$.when.apply($, array_of_promises).then(
successCallback function(){
// Loop over the arguments to control errors??
},
failCallback function(){
}
);
Where would I be able to detect the error? Do I get it in the 'error handling function'? Do I have to check in the 'success function' looping over the argument variable for checking that all the ajax calls were successfully done?
Upvotes: 2
Views: 989
Reputation: 664513
$.when.apply(array_of_promises)
Notice that the first argument of apply
is missing here, pass a $
or null
.
what happens when one of those ajax calls fail?
The jQuery.when
docs say:
In the case where multiple Deferred objects are passed to jQuery.when, the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed. The method will resolve its master Deferred as soon as all the Deferreds resolve, or reject the master Deferred as soon as one of the Deferreds is rejected. If the master Deferred is resolved, it is passed the resolved values of all the Deferreds that were passed to jQuery.when. For example, when the Deferreds are jQuery.ajax() requests, the arguments will be the jqXHR objects for the requests, in the order they were given in the argument list.
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. If you need to perform additional processing for this case, such as canceling any unfinished ajax requests, you can keep references to the underlying jqXHR objects in a closure and inspect/cancel them in the failCallback.
Where would I be able to detect the error? Do I get it in the 'error handling function'?
Yes.
Do I have to check in the 'success function' looping over the argument variable for checking that all the ajax calls were successfully done?
No. If the error handler is called, the success function is not. The success function will only by called if there was no error.
Upvotes: 1
Reputation: 9614
Deffered.then incorporates the .done()
and .fail()
. So my guess would be that you'd have your first callback as the success/.done()
and the second as error/.fail()
.
$.when.apply(array_of_promises).then(successCallback, failCallback);
successCallback function(){
...
}
failCallback function() {
...
}
Api - $.then()
Upvotes: 1