在角,什么是对承诺的误差和捕捉功能之间的概念上的差异?误差、差异、概念上、功能

2023-09-13 02:54:34 作者:微凉徒眸意

我终于得到了角承诺的错误处理下来,但它是反直觉给我。我预计到失败回调处理的错误,而是我不得不使用一个陷阱。

我为什么执行catch,而不是失败的回调不太理解概念

我所期待的:

  SomeAsyncService.getData()。然后(功能(结果){    //调用成功。    //在此块code抛出一个错误。},功能(错误){    //我希望在这里处理错误。}); 

最终什么工作。

  SomeAsyncService.getData()。然后(功能(结果){    //调用成功。    //在此块code抛出一个错误。})赶上(功能(错误){    //当错误实际上是抓住了。}); 

如果有处理错误的承诺一个更合适的方式,让我知道。

解决方案

第二个参数应该几乎从不照字面应用code,同时还采用了首次使用。它主要是关于不同的实现之间的诺言库的互操作性。

相对误差是什么 相对误差和绝对误差的区别

您应该总是使用 .catch 除非您特别有,你需要一些奇怪的角落情况下。然后(成功的情况下,失败)

请参阅The 。然后(成功,失败)反模式。

此外Q库(该一个角$ q被基于)具有在其自述

I finally got Angular promise error handling down but it was counter-intuitive to me. I expected errors to be handled by the failure callback but instead I had to use a catch.

I don't quite understand conceptually why the catch is executed rather than the failure callback.

What I expected:

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

What eventually worked.

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. 
});

If there is a more appropriate way to handle promise errors, let me know.

解决方案

The second argument should be almost never be used literally in application code while also using the first. It is mostly about promise library interoperability between different implementations.

You should always use .catch unless you specifically have some weird corner case where you need .then(succcess, fail).

See The .then(success, fail) anti-pattern.

Also Q library (The one angular $q is based on) has similar section in their readme