【问题标题】:In Angular, what's the conceptual difference between the error and catch functions for promises?在 Angular 中,promise 的 error 和 catch 函数之间的概念区别是什么?
【发布时间】:2013-11-04 22:59:26
【问题描述】:

我终于得到了 Angular promise 错误处理,但这对我来说是违反直觉的。我预计错误将由失败回调处理,但我不得不使用 catch。

我不太明白为什么要执行 catch 而不是失败回调。

我的预期:

SomeAsyncService.getData().then(function (result) {
    // The call is successful.
    // Code in this block throws an error.
}, function (error) {
    // I expected to handle errors here.
});

什么最终奏效了。

SomeAsyncService.getData().then(function (result) {
    // The call is successful.
    // Code in this block throws an error.
}).catch(function (error) {
    // Where the error is actually caught. 
});

如果有更合适的方式来处理 promise 错误,请告诉我。

【问题讨论】:

    标签: angularjs promise


    【解决方案1】:

    第二个参数几乎不应该在应用程序代码中按字面意思使用,同时也要使用第一个参数。它主要是关于不同实现之间的承诺库互操作性。

    你应该总是使用.catch,除非你特别有一些奇怪的角落需要.then(succcess, fail)

    The .then(success, fail) anti-pattern

    还有 Q 库(一个角度 $q 是基于)has similar section in their readme

    【讨论】:

      【解决方案2】:

      我认为你有点误解了 Promise 的工作原理。

      在您的第一个代码块中,只有一个 promise 对象,它是 SomeAsyncService.getData()。此处未调用 errorCallback,因为该承诺已解决。

      在第二个代码块中,实际上有 2 个您正在使用的 promise 对象。请注意,.then()“返回一个新的承诺,该承诺通过 successCallback 的返回值 errorCallback 解决或拒绝”。所以发生的事情是你从SomeAsyncService.getData().then(...)返回的第二个promise中发现了错误。

      【讨论】:

      • 如果说失败回调仅在前一个promise失败时执行,但是如果链中的任何promise抛出错误,catch就会执行?
      • 你说对了一部分。如果链中任何先前的 Promise 抛出错误并且该错误尚未处理,则 Catch 将执行。
      【解决方案3】:

      由 angularJS documentation for $q:

      方法

      then(successCallback, errorCallback, notifyCallback) – 不管 当承诺已经或将要解决或拒绝时,然后调用一个 成功或错误回调在结果后立即异步 可用。

      .....

      catch(errorCallback) – promise.then(null, errorCallback) 的简写

      您发布的两段代码完全相同。

      【讨论】:

        猜你喜欢
        • 2012-03-23
        • 2019-05-17
        • 2012-06-02
        • 2023-03-10
        • 2016-04-24
        • 1970-01-01
        • 2011-01-13
        • 2011-03-07
        • 2023-03-08
        相关资源
        最近更新 更多