【问题标题】:Error Handling and Recovery with jQuery DeferredjQuery Deferred 的错误处理和恢复
【发布时间】:2016-02-24 22:37:14
【问题描述】:

我正在使用 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 以进一步阐明我的意思。

【问题讨论】:

    标签: javascript jquery promise jquery-deferred


    【解决方案1】:

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

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

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

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

    除了需要返回一个已实现的 jQuery 承诺之外,这就像 ES6 then 方法一样,其中 catch.then(null, …) 的同义词。

    【讨论】:

      猜你喜欢
      • 2014-02-20
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      相关资源
      最近更新 更多