最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I force jQuery DeferredAjax to execute fail handler after it has been resolved? - Stack Overflow

programmeradmin3浏览0评论

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 acplish 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){
         ...
      })

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 acplish 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){
         ...
      })
Share Improve this question asked Jan 14, 2014 at 10:09 lordvladlordvlad 5,3472 gold badges25 silver badges44 bronze badges 11
  • 1 a Deferred object's state can be set only once.... – Arun P Johny Commented Jan 14, 2014 at 10:11
  • I know that. Is there still any way to force the execution of failure handlers? – lordvlad Commented Jan 14, 2014 at 10:13
  • technically you can use a goto. But in practice it's better not to do it – Fabrizio Calderan Commented Jan 14, 2014 at 10:13
  • 2 What about using .always()? – Nabil Kadimi Commented Jan 14, 2014 at 10:18
  • @NabilKadimi, then i would need an additional check, whether always was called after a success or failure, but it's an idea – lordvlad Commented Jan 14, 2014 at 10:26
 |  Show 6 more ments

1 Answer 1

Reset to default 16

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){
    …
  });
发布评论

评论列表(0)

  1. 暂无评论