jQuery延迟的错误处理和恢复 [英] Error Handling and Recovery with jQuery Deferred

查看:111
本文介绍了jQuery延迟的错误处理和恢复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery,并且知道此问题是因为jQuery.Deferred实现与Promises/A +不兼容.我不想使用任何其他库来解决这个问题.

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.

通过这种方式,是否有一种方法可以从$.Deferred().fail()回调中恢复,使我返回到成功链?这可以通过then()的多回调形式实现,但是到目前为止,我还没有找到使用.fail()

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()

然后:

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");
});

对于我来说,我只需要检查是否有故障,设置一个标志并继续执行我的工作即可.我只是在然后"示例中不需要并行成功处理程序.

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.

这里是 jsFiddle ,以进一步阐明我的意思.

Here is a jsFiddle to further clarify what I mean.

推荐答案

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

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

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

由于只有then启用链接,因此您应该使用

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");
});

除了需要返回兑现的jQuery承诺外,这与 ES6 then 方法,其中 catch .then(null, …)的同义词.

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, …).

这篇关于jQuery延迟的错误处理和恢复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆