4

I am using jQuery and am aware that this issue is because the jQuery.Deferred implementation is not Promises/A+ compiant. I do not want to use any other libraries to solve this.

With that out of the way, is there a way to recover from a $.Deferred().fail() callback such that I am returned back to the success chain? This is possible with the multi-callback form of then() but so far I have not found a solution using .fail()

then:

asyncThatWillFail().then(function () {
    // useless callback
}, function () {
    console.log("error");
    return $.Deferred().resolve();
}).then(function () {
    console.log("continuing on success chain");
});

fail (does not work):

asyncThatWillFail().fail(function () {
    console.log("error");
    return $.Deferred().resolve();
}).then(function () {
    console.log("continuing on success chain");
});

In my case I only need to check for failure, set a flag, and continue with what I was doing. I simply don't need the parallel success handler in the "then" example.

Here is a jsFiddle to further clarify what I mean.

thedarklord47
  • 3,183
  • 3
  • 26
  • 55

1 Answers1

3

No, you cannot use .fail for that. However, you don't need to pass a function as the first argument to .then:

the arguments can be null if no callback of that type is desired.

Since only then enables chaining, you should use

asyncThatWillFail().then(null, function () {
    console.log("error");
    return $.Deferred().resolve();
}).then(function () {
    console.log("continuing on success chain");
});

Apart from the need to return a fulfilled jQuery promise, this is just like the ES6 then method where catch is a synonym for .then(null, …).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375