Error Handling and Recovery with jQuery Deferred

半腔热情 提交于 2019-12-22 08:26:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!