8

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){
         ...
      })
lordvlad
  • 5,200
  • 1
  • 24
  • 44

1 Answers1

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){
    …
  });
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • i knew, it had to be possible! thanks. i've came across the `then` handler, but never quite understood its purpose. – lordvlad Jan 14 '14 at 15:41
  • But when we return new `$.Deferred()` object, we loose access to `.abort()` method `jqXHR` has? `$.Deferred()` object doesn't have it. – Nik Sumeiko Mar 15 '16 at 12:02
  • @manakor: You always loose that when you use `then`, this doesn't have anything to do with the callback return value. if you need `abort`, store a reference to the `jqXHR` object before chaining promise callbacks to it. – Bergi Mar 15 '16 at 16:17