【问题标题】:Accessing jQuery ajax error in Promise.all catch在 Promise.all 中访问 jQuery ajax 错误
【发布时间】:2018-03-26 11:56:32
【问题描述】:

我在 Promise.all 中使用 jQuery 运行多个 ajax 请求:

const firstFetchPromise = $.ajax({ url: '/some/url' });
const secondFetchPromise = $.ajax({ url: '/another/url' });

Promise.all([ firstFetchPromise, secondFetchPromise ])
  .then(results => storeResults(results))
  .catch(e => {
    console.log(e); // e is a promise, how to get the ajax error?
  });

为了测试错误处理,我关闭了 ajax 请求从中获取数据的服务器,并且浏览器使用 URL 记录了 ERR_CONNECTION_REFUSE。

catch 语句记录了一些看起来像承诺的东西:

abort:ƒ (a),
always:ƒ (),
complete:ƒ (),
done:ƒ (),
error:ƒ (),
fail:ƒ (),
getAllResponseHeaders:ƒ (),
getResponseHeader:ƒ (a),
overrideMimeType:ƒ (a),
pipe:ƒ (),
progress:ƒ (),
promise:ƒ (a),
readyState:0,
responseText:"",
setRequestHeader:ƒ (a,b),
state:ƒ (),
status:0,
statusCode:ƒ (a),
statusText:"error",
success:ƒ (),
then:ƒ (),

如何获取承诺中的 ajax 错误,以便在网页中显示可读的错误消息?

【问题讨论】:

  • e is a promise - 不应该 - 你显示的控制台日志看起来不像一个承诺(getResponseHeader、getAllResponseHeaders、setRequestHeader、overrideMimeType 都看起来像 XHR 方法)
  • 很可能是这样,我是新的承诺,更习惯于回调。我已经用完整的对象更新了问题。我期待会有一些与网络相关的错误消息。对象作为键,如承诺,然后,失败等,所以我认为这是一个承诺。

标签: javascript jquery ajax promise es6-promise


【解决方案1】:

Promise.all() 以第一个拒绝的承诺的原因拒绝。

在这种情况下,即$.ajaxjqXHR

你会得到这样的错误:

Promise.all([ firstFetchPromise, secondFetchPromise ])
  .then(results => storeResults(results))
  .catch(e => {
    console.log(e.responseText); // Server response

    e.fail(function (jqXHR, textStatus, errorThrown) {
      console.log(e === jqXHR);  // true
      console.log(textStatus);   // 'error'
      console.log(errorThrown);  // 'HTTP/2.0 404'
    });
});

【讨论】:

  • 谢谢,这是有道理的。有没有办法获取有关错误的信息?我原以为浏览器不仅仅是“错误”。
  • 可以在e.responseText获取服务器响应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 2020-03-27
  • 1970-01-01
相关资源
最近更新 更多