Sorskoot Sorskoot - 5 months ago 42
jQuery Question

Is there a way to continue after one deferred fails?

I'm handling an unknown number of ajax requests. The request could fail in a 404. This causes the whole chain to fail.

Is there a way to continue after one deferred fails?

var deferreds = [];
// fill deferreds with a number of ajax requests.
$.when.apply($, deferreds)
.done(function(){
// handle done
}).fail(function(){
// handle fail
// would like to fix/resolve the failed deferred and continue with the rest
});

Answer

You have to create your own deferred object, waiting for the other deferred to succeed or fail.

var myDeferred = $.Deferred();
var origDeferred = $.ajax(...);
// if request is ok, i resolve my deferred
origDeferred.done(function() {
  myDeferred.resolve.apply(this, arguments);
});
// if request failed, i also resolve my deferred
origDeferred.fail(function() {
  myDeferred.resolve.apply(this, arguments);
});

In that case your deferred will always be resolved.