jQuery when/then/fail with concurrent ajax requests: Which request failed?

Javier picture Javier · Apr 26, 2011 · Viewed 13.7k times · Source

Imagine a scenario where we want to do something after the concurrent requests for 'foo' and 'bar' have completed successfully, or report an error if one or both of them fails:

$.when($.getJSON('foo'), $.getJSON('bar'))
  .then(function(foo, bar) {
    console.log( 'I fire if BOTH requests are successful!' );
  })
  .fail(function() {
    console.log( 'I fire if one or more requests failed.' );
  });

How can I determine if 1) the request for 'foo' failed, or 2) the request for 'bar' failed, or 3) if both failed?

Answer

Sean Vieira picture Sean Vieira · Apr 26, 2011

Simply add a fail call to each promise that is returned from $.getJSON:

function make_error_handler(msg) {
    return function() { console.log(msg); };
}

$.when($.getJSON('foo').fail(make_error_handler("foo failed"))
            , $.getJSON('bar').fail(make_error_handler("bar failed")))
  .then(function(foo, bar) {
    console.log( 'I fire if BOTH requests are successful!' );
  })
  .fail(function() {
    console.log( 'I fire if one or more requests failed.' );
  });

If you need more fine-grained control you can overload $.getJSON to return additional information to the fail function -- see jQuery's documentation on deferred.rejectWith