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

前端 未结 5 2113
忘了有多久
忘了有多久 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:14

    Would something like this work out for you? You just need to return your own Deferred/Promise so that the original one isn't rejected too soon.

    Example/test usage: http://jsfiddle.net/4LT2a/3/

    function doSomething() {
        var dfr = $.Deferred();
    
        (function makeRequest() {
            $.ajax({
                url: "someurl",
                dataType: "json",
                success: dfr.resolve,
                error: function( jqXHR ) {
                    if ( jqXHR.status === 401 ) {
                        return makeRequest( this );
                    }
    
                    dfr.rejectWith.apply( this, arguments );
                }
            });
        }());
    
        return dfr.promise();
    }
    

提交回复
热议问题