在Promise.all catch中访问jQuery ajax错误

时间:2017-10-14 13:49:11

标签: javascript jquery ajax promise es6-promise

我在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错误,以便在网页中显示可读的错误消息?

1 个答案:

答案 0 :(得分:0)

Promise.all()拒绝承认拒绝的第一个承诺。

在这种情况下,这是$.ajax' s jqXHR

你可以得到这样的错误:

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'
    });
});
相关问题