15

我终于得到了 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 错误,请告诉我。

4

3 回答 3

16

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

.catch除非您特别需要一些奇怪的角落案例,否则您应该始终使用.then(succcess, fail).

.then(success, fail)参阅反模式

Q库(一个角度 $q 是基于)在他们的自述文件中有类似的部分

于 2013-10-25T21:12:18.027 回答
7

我认为您对承诺的工作方式略有误解。

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

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

于 2013-10-25T19:42:14.770 回答
-1

通过$q 的angularJS文档:

方法

then(successCallback, errorCallback, notifyCallback) – 无论承诺何时被解决或被拒绝,只要结果可用,就会异步调用成功或错误回调之一。

......

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

您发布的两段代码是相同的。

于 2013-10-25T17:57:23.337 回答