在Angular中,promises的错误和catch函数之间的概念差异是什么?

Jas*_*son 15 promise angularjs

我终于得到了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.
});
Run Code Online (Sandbox Code Playgroud)

什么最终奏效.

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. 
});
Run Code Online (Sandbox Code Playgroud)

如果有更合适的方法来处理承诺错误,请告诉我.

Esa*_*ija 16

第二个参数应该几乎从不在应用程序代码中直接使用,同时也使用第一个.它主要是关于不同实现之间的promise库互操作性.

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

.then(success, fail)反模式.

此外,Q库(一个角度为$ q的基础)在其自述文件中也有类似的部分


Roy*_*els 7

我认为你有点误解承诺是如何运作的.

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

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