Skip to content

Instantly share code, notes, and snippets.

@gajewsk2
Last active December 7, 2015 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gajewsk2/9de8f2551659505387d6 to your computer and use it in GitHub Desktop.
Save gajewsk2/9de8f2551659505387d6 to your computer and use it in GitHub Desktop.
retry from SO
//http://stackoverflow.com/questions/11793430/retry-a-jquery-ajax-request-which-has-callbacks-attached-to-its-deferred
//http://jsfiddle.net/gLedx/2/
$.ajaxPrefilter(function(opts, originalOpts, jqXHR) {
// you could pass this option in on a "retry" so that it doesn't
// get all recursive on you.
if ( opts.retryAttempt ) {
return;
}
var dfd = $.Deferred();
// if the request works, return normally
jqXHR.done(dfd.resolve);
// if the request fails, do something else
// yet still resolve
jqXHR.fail(function() {
if ( jqXHR.status === 404 ) {
dfd.resolveWith(this, ["I cheated and loaded this from 'cache'"]);
} else {
dfd.rejectWith( this, arguments );
}
});
// NOW override the jqXHR's promise functions with our deferred
return dfd.promise(jqXHR);
});
$.ajax("/not/a/url").done(function(data) {
console.log("done", this, data);
}).fail(function() {
console.log("fail", this, arguments);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment