重试失败的jQuery.ajax请求
我需要创建一个函数,在给定限制之前重试失败的ajax请求,但我需要确保承诺仅在超过最大重试次数时被拒绝,如下所示:重试失败的jQuery.ajax请求,jquery,jquery-deferred,Jquery,Jquery Deferred,我需要创建一个函数,在给定限制之前重试失败的ajax请求,但我需要确保承诺仅在超过最大重试次数时被拒绝,如下所示: function my_ajax(...) { ... } // then I use it this way return $.when(my_ajax('foo.json'), my_ajax('bar.json')) 为了使用jQuery.when,只应返回my_ajax的一个承诺,该承诺应在解析内部jQuery.ajax时解析,并且仅在进行最大重试次数时才被拒绝 我的代
function my_ajax(...) { ... }
// then I use it this way
return $.when(my_ajax('foo.json'), my_ajax('bar.json'))
为了使用jQuery.when,只应返回my_ajax
的一个承诺,该承诺应在解析内部jQuery.ajax时解析,并且仅在进行最大重试次数时才被拒绝
我的代码是这样的:
function do_ajax(args, dfd, attempt) {
dfd || (dfd = $.Deferred());
attempt || (attempt = 1);
$.ajax(args).then(dfd.resolve, function(xhr, text_status, error_thrown) {
console.error(/* something useful */);
attempt++;
if(attempt > 3) {
dfd.reject(xhr, text_status, error_thrown);
} else {
do_ajax(args, dfd, attempt);
}
});
return dfd.promise();
}
// in some random code
return $.when(do_ajax({url:'foo.json'}), do_ajax({url:'bar.json'});
这对我来说很有用,但有点难以理解。问题是:有没有更好(更容易阅读)的方法
*-事实上,有时我没有测试失败,但当第一个ajax请求成功时,我可以正常工作。我认为您的代码是正确的方法,将您的调用封装在一个新的延迟中,并返回它,直到达到所有尝试 您可以尝试在匿名函数中包含递归调用,以提高可读性 我是这样写的:
function doAjax(ajaxArgs, attempt) {
// the wrapped returned dfd
var wrappedDfd = $.Deferred();
// your nested call using attempt counter
(function nestedCall() {
// if call succed, resolve the wrapped dfd
$.ajax(ajaxArgs).then(wrappedDfd.resolve, function() {
// update attempt counter
attempt--;
if (attempt > 0) {
// try another call
nestedCall();
} else {
// max try reached, reject wrapped dfd
wrappedDfd.reject();
}
});
})();
return wrappedDfd.promise();
};
这与您的代码非常相似
这是你的电话号码。出于测试目的,我用模拟工厂调用替换了doAjax参数,但代码保持不变
希望对您有所帮助。基于的答案和其他一些人的回答,SO创建了一个jQuery插件:(),并且:
jquery.ajaxRetry
范例
$.ajax({
// Retry this request up to 2 times
shouldRetry: 2
});
$.ajax(options).retry({times:3, timeout:3000}).then(function(){
alert("success!");
});
- 可以无限期重试
- 可以重试
n次
- 可以运行函数并在
中计算为shouldRetry
或true
,以确定是否应继续重试false
$.ajax({
// Retry this request up to 2 times
shouldRetry: 2
});
$.ajax(options).retry({times:3, timeout:3000}).then(function(){
alert("success!");
});
- 可以重试
n次
- 可以指定重试之间的等待时间
- 可以指定要重试的状态代码