angularjs - 在 Angular 中,promise 的 error 和 catch 函数在概念上的区别是什么?

标签 angularjs promise

我终于解决了 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/

相关文章:

angularjs - 使用 JWT 处理 401(未经授权)angularjs 身份验证

javascript - Angular 服务/ Controller 不返回 promise ?

javascript - 从 parse.com 查询的 javascript 对象获取数据

angularjs - 如何访问行选择上的行数据

javascript - AngularJS:如何修改 document.onload 中的服务?

Angularjs ng-model-options 不起作用。

javascript - 避免在 angularjs 指令中引用父范围

javascript - 如何同步 Promise 对象?

javascript - 返回带 .then() 和不带 .then() 的 Promise 有什么区别?

javascript - Firefox:Promise.then 不被异步调用