Last active
December 7, 2015 15:17
-
-
Save gajewsk2/9de8f2551659505387d6 to your computer and use it in GitHub Desktop.
retry from SO
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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