I need to create a function that retries a failed ajax request until a given limit, but I need to ensure the promise is only rejected when the maximum of retries was exceeded, like this:
function my_ajax(...) { ... }
// then I use it this way
return $.when(my_ajax('foo.json'), my_ajax('bar.json'))
In order to work with jQuery.when, only one promise should be returned of my_ajax
, which should be resolved when the internal jQuery.ajax is resolved, and rejected only when the maximum of retries was made.
The code I made is this:
function do_ajax(args, dfd, attempt) {
dfd || (dfd = $.Deferred());
attempt || (attempt = 1);
$.ajax(args).then(dfd.resolve, function(xhr, text_status, error_thrown) {
console.error(/* something useful */);
attempt++;
if(attempt > 3) {
dfd.reject(xhr, text_status, error_thrown);
} else {
do_ajax(args, dfd, attempt);
}
});
return dfd.promise();
}
// in some random code
return $.when(do_ajax({url:'foo.json'}), do_ajax({url:'bar.json'});
This works for me*, but it's kind of hard to understand. The question is: is there a better (and easier to read) way to do it?
* - Actually I didn't tested to fail sometimes, but I works fine when the first ajax request is successful.