使用jQuery Deferred进行错误处理和恢复

4
我正在使用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以进一步澄清我的意思。
1个回答

3
不,你不能使用.fail来做那个。然而,你不需要将函数作为第一个参数传递给.then

如果不需要该类型的回调,则参数可以为null

由于只有then支持链式调用,所以应该使用

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

除了需要返回一个已完成的jQuery promise之外,这与ES6 then方法非常相似,其中catch.then(null, …)的同义词。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接