问题
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.
回答1:
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, …)
.
来源:https://stackoverflow.com/questions/35614632/error-handling-and-recovery-with-jquery-deferred