javascript - 如何使用 Promise 处理失败的 ajax 请求

标签 javascript jquery ajax promise

我正在发出多个像这样的ajax请求

imgPromises = [];

imgPromise1 = $.ajax({
  url: s3Url,
  type: "POST",
  data: s3FormData,
  mimeType: "multipart/form-data",
  contentType: false,
  cache: false,
  processData: false
}).done(function(data, status, formXHR) {
  x = formXHR['responseText'].toString();
  var uploadedUrl = x.match("<Location>(.*)</Location>")[1];
  if ($(this).attr('id').startsWith('inp')) {
    if ($(this).attr('id').startsWith('inp')) $('footer').css('background-image', 'url(' + uploadedUrl + ')');
    footerBackground = $('footer').css('background');
  }
}).fail(function() {
  console.log("in ajax fail");
}.bind(this));

imgPromises.push(imgPromise1);

imgPromise2 = $.ajax({
  url: s3Url,
  type: "POST",
  data: s3FormData,
  mimeType: "multipart/form-data",
  contentType: false,
  cache: false,
  processData: false
}).done(function(data, status, formXHR) {
  x = formXHR['responseText'].toString();
  var uploadedUrl = x.match("<Location>(.*)</Location>")[1];
  if ($(this).attr('id').startsWith('inp')) {
    if ($(this).attr('id').startsWith('inp')) $('footer').css('background-image', 'url(' + uploadedUrl + ')');
    footerBackground = $('footer').css('background');
  }
}).fail(function() {
  console.log("in ajax fail");
}.bind(this));

imgPromises.push(imgPromise2);

Promise.all(imgPromises.then(function() {});

如果任何一个 Promise(imgPromise1imgPromise2)失败,则它不会转到 Promise.all

我希望在任何情况下它都应该转到 Promise.all

最佳答案

您在错误的地方使用了then

const Fail = function(error){this.error=error;};//special Fail type value
const isFail = o=>(o&&o.constructor)===Fail;//see if item passed is fail type
const isNotFail = o => !isFail(o);//see if item passed is not fail type
Promise.all(imgPromises
  .map(
    p=>Promise.resolve(p)/**convert to real promise*/
  ).map(
    p=>p.catch(error=>new Fail(error))//single request failed, resolve with Fail value
  )
)
.then(function (responses) {
  // successes = responses.filter(isNotFail)
  // failed = responses.filter(isFail)
})
.catch(function (err) {
  //handle error
});

MDN page for Promise.all

关于javascript - 如何使用 Promise 处理失败的 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50800671/

相关文章:

jquery - 当用户到达页面底部时如何显示div?

javascript - 如何在 Gmap3 中添加多个标记?

javascript - Gmail 中 while(1) 的作用是什么

jQuery .data 与 eventData

javascript - 如何使用jquery ajax请求将图像文件从本地机器发送到服务器

php - 验证中 AJAX 的安全风险?

javascript - 防止物体离开相机边界

java - 如何防止Applet跨网页卸载?

javascript - 找出更改页面中特定 html 内容的 javascript 代码的最佳方法是什么

javascript - 将 Ngu Carousel 与 Angular 4 一起使用时出错