Skip to content

Instantly share code, notes, and snippets.

@brownsoo
Last active January 8, 2023 14:39
Show Gist options
  • Save brownsoo/1402644948a63dfe894a6bb0150a7bcc to your computer and use it in GitHub Desktop.
Save brownsoo/1402644948a63dfe894a6bb0150a7bcc to your computer and use it in GitHub Desktop.
jquery ajax retry workout
// extends ajax
$.ajax = (($oldAjax) => {
var df = $.Deferred();
// on fail, retry by creating a new Ajax deferred
function check(self, status) {
console.log("check " + status + " => " + self.retries);
const shouldRetry = status != 'success' && status != 'parsererror';
if (shouldRetry && self.retries > 0) {
setTimeout(() => {
console.log("retry " + self.retries);
$.ajax(self);
}, self.retryInterval || 100);
}
}
function failed(jqXHR, status, e) {
if (this.retries - 1 <= 0) {
// 재시도 횟수가 끝나면, 오류 보내기
df.reject(KfError.convertKfError(jqXHR, this.url));
} else {
this.retries --;
check(this, 'retry', this.retries);
}
}
function done(res, textStatus, jqXHR) {
if (!res.success) { // 200코드지만, 응답에 실패라면 오류로 처리
if (this.retries - 1 <= 0) {
df.reject(KfError.createResponseError(res, this.url));
} else {
this.retries --;
check(this, 'retry', this.retries)
}
} else {
df.resolve(res, textStatus, jqXHR);
}
}
return function (settings) {
console.log("==>" + settings.url);
$oldAjax(settings)
.fail(failed)
.done(done);
return df;
};
})($.ajax);
function createRequest(url) {
return $.ajax({
type: 'GET',
url: url,
timeout: 2000,
retries: 3,
retryInterval: 1000
});
}
// testing
$(async function () {
try {
let res = await createRequest(Rest.correctUrl('/auth/refresh'));
console.log('ok res');
} catch (e) {
console.log('결국 error : ' + e.message);
console.log(e);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment