I\'m trying to implement a system of retrying ajax requests that fail for a temporary reason. In my case, it is about retrying requests that failed with a 401 status code be
This is a great question that I just faced too.
I was daunted by the accepted answer (from @gnarf), so I figured out a way that I understood easier:
var retryLimit = 3;
var tryCount = 0;
callAjax(payload);
function callAjax(payload) {
tryCount++;
var newSaveRequest = $.ajax({
url: '/survey/save',
type: 'POST',
data: payload,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
error: function (xhr, textStatus, errorThrown) {
if (textStatus !== 'abort') {
console.log('Error on ' + thisAnswerRequestNum, xhr, textStatus, errorThrown);
if (tryCount <= retryLimit) {
sleep(2000).then(function () {
if ($.inArray(thisAnswerRequestNum, abortedRequestIds) === -1) {
console.log('Trying again ' + thisAnswerRequestNum);
callAjax(payload);//try again
}
});
return;
}
return;
}
}
});
newSaveRequest.then(function (data) {
var newData = self.getDiffFromObjects(recentSurveyData, data);
console.log("Answer was recorded " + thisAnswerRequestNum, newData);//, data, JSON.stringify(data)
recentSurveyData = data;
});
self.previousQuizAnswerAjax = newSaveRequest;
self.previousQuizAnswerIter = thisAnswerRequestNum;
}
function sleep(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
Basically, I just wrapped the entire Ajax call and its callbacks into one function which can get called recursively.