【问题标题】:Chaining ajax calls using then, handling expected failure使用 then 链接 ajax 调用,处理预期的失败
【发布时间】:2014-05-29 21:18:56
【问题描述】:

我有这样的电话:

$.ajax({url:"url", ....}).then(function(response) {
  if (response.sucess) {
    return $.ajax({.....});
  }
  else {
    //what do I return here so the next then doesn't fire but no error is raised?
  }
}).then(function(response2) {
   //....Do more stuff
});

所以第一个ajax 调用返回一个成功标志。如果这成功了,那么我希望它继续下去。如果不是,我想阻止下一个then 触发。我不确定我应该从第一个返回什么,然后success == false?

我觉得我应该返回 $.Deferred,因为这是 then 所期望的,但我不确定如何执行此操作,因为我没有触发另一个 deferred 操作。

【问题讨论】:

    标签: jquery jquery-deferred


    【解决方案1】:

    想通了。需要回一个.reject();

    $.ajax({url:"url", ....}).then(function(response) {
      if (response.sucess) {
        return $.ajax({.....});
      }
      else {
        return $.Deferred().reject();
      }
    }).then(function(response2) {
       //....Do more stuff
    });
    

    【讨论】:

    • 这有点学术,但按道理应该是return $.Deferred().reject().promise();。
    • 与return $.ajax(...) 相提并论。一般来说,Deferred 对创建它们的函数是私有的,只有派生的 Promise 才会显示给调用函数。我之所以在这种情况下说它是学术性的,是因为您的 Deferred 以拒绝状态返回,因此无法干预。
    猜你喜欢
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 2023-03-30
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多