javascript - jQuery ajax - 仅当所有重试失败时才触发失败回调函数

标签 javascript jquery ajax

我将 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/

相关文章:

javascript - Sencha : Two lists showing different content from the same store. 可能吗?

javascript - jquery 检查 URL 是否已经有查询字符串

javascript - serializeArray 函数不返回输入字段值和 tinyMCE 文本区域值

JavaScript 在 URL 中添加 #,新页面打开一半

c# - HTMLAgilityPack 加载 AJAX 内容以进行抓取

javascript - 原型(prototype)编程中的对象和原型(prototype)有什么区别?

javascript - 如何在不刷新的情况下编辑和删除MySQL数据库的记录?

javascript - window.onunload() 在 Firefox 中不起作用?在 IE 中工作吗?

javascript - 函数隐藏在javascript中

javascript - 使用ajax请求进行 Angular 翻译