我终于解决了 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 错误,请告诉我。
最佳答案
第二个参数应该几乎永远不会在应用程序代码中逐字使用,同时也使用第一个参数。它主要是关于不同实现之间的 promise 库互操作性。
您应该始终使用 .catch
除非你特别需要一些奇怪的 Angular 落案例 .then(succcess, fail)
.
见 The .then(success, fail)
anti-pattern .
还有 Q 库(基于 $q 的一个 Angular )has similar section in their readme
关于angularjs - 在 Angular 中,promise 的 error 和 catch 函数在概念上的区别是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19596384/