Roswell Studios

139 Fulton Street, Ste 132
New York, NY 10038

Fault tolerant jQuery .when()

— January 8, 2018

When getting data from a set of REST endpoints, some times the correct result comes back as an HTTP error. If you were managing the set of ajax calls with jQuery’s .when, it will fail/stop as soon as one of the items returns an error. I still want the rest of the data, though.

function failTolerantPromises(promises) {
return $.map(promises, function(p) {
var dfd = $.Deferred()
p.always(function() { dfd.resolve() })
return dfd.promise();

called with

var sloaders = [];
//akeys is now set, so submissions has all the data it needs
$.each(submissions, function(cid,uids){
$.each(uids, function(x,uid){
$.when.apply($, failTolerantPromises(sloaders)).then(function() {
//done stuff

where getSubmission() returns $.ajax(). That particular call fails with “not authorized” if there aren’t any submissions, or possibly too many submissions. I don’t know why it does that, but no submissions is just no submissions, not a failure state. Altering the ajax promise result from error to resolve via .always in a new promise allows .when to proceed with all the data it has.

Back to all