Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

javascript - Can I force jQuery Deferred/Ajax to execute fail handler after it has been resolved?

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){
         ...
      })
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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){
    …
  });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...