【问题标题】:What is the difference between .catch and .fail in jQuery?jQuery 中的 .catch 和 .fail 有什么区别?
【发布时间】:2017-09-09 08:56:20
【问题描述】:

.fail 的简短文档说:

添加当 Deferred 对象被拒绝时要调用的处理程序。

.catch 的简短文档完全相同:

添加当 Deferred 对象被拒绝时要调用的处理程序。

来源:http://api.jquery.com/category/deferred-object/

这两种方法接受的参数似乎不同, .catch 声明 .catch.then(null, fn) 的别名

在某些情况下我应该使用.fail,而在其他情况下我应该使用.catch

或者......如果我只有一个功能......是否遵循可互换的命令并且它们仅出于兼容性/历史原因而存在?

a) .fail(fn)

b) .catch(fn)

c) .then(null, fn)

我创建了一个 jsFiddle:

https://jsfiddle.net/sq3mh9j5/

如果有区别,请您提供一些示例,因为我是 jquery 新手,还不熟悉所有承诺条款。

.catch 的文档为什么没有引用 .fail 的文档并说明区别/相似之处?

编辑 我在 3.0 发行说明中发现 .then 的行为发生了变化。 https://blog.jquery.com/2015/07/13/jquery-3-0-and-jquery-compat-3-0-alpha-versions-released/ 尽管如此,我仍然不确定何时使用 .fail 以及何时使用 .catch。

【问题讨论】:

    标签: jquery promise deferred


    【解决方案1】:

    catchfail 略有不同,catch 将返回一个新的(已解决的)承诺,而 fail 将返回原始承诺。

    // This will only output "fail"
    $.Deferred()
      .reject(new Error("something went wrong"))
      .fail(function() {
        console.log("fail");
      })
      .then(function() {
        console.log("then after fail");
      })
    
    // This will output "catch" and "then after catch"
    $.Deferred()
      .reject(new Error("something went wrong"))
      .catch(function() {
        console.log("catch");
      })
      .then(function() {
        console.log("then after catch");
      })
    

    Note that catch(fn) is an alias of then(null, fn).

    【讨论】:

    • "will re-resolve the promise" 非常具有误导性。重要的一点是它返回一个新的、独特的承诺(就像then)。
    • 啊,明白了。我不太知道如何描述它 - 我会更新我的答案。谢谢
    • 因此,如果我想break/exit 正常工作流程出错...我将使用fail(第一个示例),如果我想实现always 子句,我使用 then在catch 之后(第二个例子)。
    • @Stefan 我建议永远不要使用faildone
    【解决方案2】:

    所以我认为主要的区别在于你能从中得到什么。

    catch 允许您运行单个函数。

    失败允许您运行许多函数。

    除此之外,我同意您的发现。它们非常相似。

    我添加了一个示例代码来展示 fail 将如何运行这两个函数,而 catch 只会运行一个。

     $.ajax({
                url: "abc"
            }).done(function (data) {
    
            }).fail(function () {
                alert("a");
            }, function () {
                alert("b");
            })
                    .catch(function () {
                        alert("c");
                    }, function () {
                        alert("d");
                    });
    

    如果你运行它,你会得到 'a','b','c' 然后 'd' 不会运行。

    我希望这个简单的例子能展示出不同之处。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-22
      • 2015-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 2010-12-19
      相关资源
      最近更新 更多