Retry a jquery ajax request which has callbacks attached to its deferred

前端 未结 5 2116
忘了有多久
忘了有多久 2020-12-04 12:42

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

5条回答
  •  星月不相逢
    2020-12-04 13:07

    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.

提交回复
热议问题