我将 ajax 与 jQuery 结合使用,因为我们知道 $.ajax
返回一个 promise ajaxPromise
。我的要求是:只有当所有ajax调用重试都失败时,ajaxPromise
才能捕获失败(我想在ajax Promise回调函数中处理错误)。
我尝试了以下代码:
function ajax(data) {
return $.ajax({
url: "...",
data: data,
triedCount: 0,
retryLimit: 3,
error: function(xhr, textStatus, errorThrown ) {
console.log("error: " + this.triedCount);
this.triedCount++;
if (this.triedCount < this.retryLimit) {
$.ajax(this);
}
}
});
}
var ajaxPromise = ajax({"id": "123"});
ajaxPromise.fail(function(xhr) {
console.log("All retries failed...");
// all retries failed, handle error
});
输出我想要的是:
error: 0
error: 1
error: 2
All retries failed...
实际上输出是:
error: 0
All retries failed...
error: 1
error: 2
看起来 fail
回调在第一次调用失败后立即触发,而我希望在所有重试失败后触发 fail
回调。
有没有办法只有当所有重试都失败时才触发ajaxPromise.fail
回调?或者还有其他选项可以做到这一点吗?
最佳答案
可以使用$.Deferred()
、.rejectWith()
;使用 $.Deferred()
的 beforeStart
调用递归函数,并将 ajaxOptions
作为参数传递;如果 this.triedCount
不小于 this.retryLimit
,则返回被拒绝的延迟对象,并将 this
设置为当前 ajax 选项,xhr
作为参数传递给链接到 ajaxPromise
.fail()
function ajax(data) {
var ajaxOptions = {
url: "...",
data: data,
triedCount: 0,
retryLimit: 3
};
return new $.Deferred(function(dfd) {
function request(opts) {
$.ajax(opts)
.fail(function(xhr, textStatus, errorThrown) {
console.log("error: " + this.triedCount);
this.triedCount++;
if (this.triedCount < this.retryLimit) {
return request(this)
} else {
dfd.rejectWith(this, [xhr])
}
})
}
request(ajaxOptions)
})
}
var ajaxPromise = ajax({
"id": "123"
});
ajaxPromise.fail(function(xhr) {
console.log("All retries failed...", xhr);
// all retries failed, handle error
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
关于javascript - jQuery ajax - 仅当所有重试失败时才触发失败回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39031150/