jQuery 延迟的错误处理和恢复

Error Handling and Recovery with jQuery Deferred

我正在使用 jQuery,我知道这个问题是因为 jQuery.Deferred 实现不符合 Promises/A+。我不想使用任何其他库来解决这个问题。

解决了这个问题,有没有办法从 $.Deferred().fail() 回调中恢复,使我返回到成功链?这可以通过 then() 的多回调形式实现,但到目前为止我还没有找到使用 .fail()

的解决方案

然后:

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

失败(不起作用):

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

在我的例子中,我只需要检查失败,设置一个标志,然后继续我正在做的事情。我根本不需要 "then" 示例中的并行成功处理程序。

这里jsFiddle进一步阐明我的意思。

不,您不能为此使用 .fail。但是,您不需要将函数作为第一个参数传递给 .then:

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

因为只有 then 启用链接,您应该使用

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

除了需要 return 履行 jQuery 承诺外,这就像 ES6 then method where catch.then(null, …) 的同义词一样。