我可以强制jQuery Deferred / Ajax在解决后执行失败处理程序吗? [英] Can I force jQuery Deferred/Ajax to execute fail handler after it has been resolved?

查看:109
本文介绍了我可以强制jQuery Deferred / Ajax在解决后执行失败处理程序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说明我想做什么的一个例子。这就是我通常会做的事情:

An example to make clear what i want to do. This is what I would usually do:

function success(data, status, jqxhr){
  if ( data.error )
    return failure(jqxhr, status, data.error);
  // process data
}
function failure(jqxhr, status, err){
  ...
}

$.ajax( ... )
  .done(success)
  .fail(failure)

有什么办法,我可以用匿名函数完成这个,就像这样吗?

Is there any way, i can accomplish this with anonymous functions only, like so?

   $.ajax( ... )
      .done(function(data, status, jqxhr){
         if(data.error)
            // what do i need to do here to jump in to the fail handler?
      })
      .fail(function(jqxhr, status, err){
         ...
      })


推荐答案


我需要做什么才能跳转到失败处理程序?

what do i need to do here to jump in to the fail handler?

不要使用已完成,但是然后映射承诺的结果。通过返回被拒绝的承诺,您可以抛出错误并拒绝产生的承诺,以便执行你的失败处理程序。

Don't use done, but then to map over the result of the promise. By returning a rejected promise you can "throw" an error and reject the resulting promise, so that your fail handler is executed.

$.ajax(…)
  .then(function(data, status, jqxhr){
    if (data.error)
      return $.Deferred().reject(data.error);
    else
      return data; // if you want to return multiple arguments, you'd use
                   // $.Deferred().resolve(data, status, jqxhr);
  })
  .done(function(data) {
    …
  })
  .fail(function(jqxhr, status, err){
    …
  });

这篇关于我可以强制jQuery Deferred / Ajax在解决后执行失败处理程序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆