如何正确捕捉承诺中的错误? [英] How to properly catch errors in promises?

查看:33
本文介绍了如何正确捕捉承诺中的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得这两件事并不等同:

I am under the impression that these two things are not equivalent:

return somePromise()
  .then()
  .then()
  .then()
  .catch(function(e) { throw e; });

return somePromise()
  .catch(function(e) { throw e; });
  .then()
  .catch(function(e) { throw e; });
  .then()
  .catch(function(e) { throw e; });
  .then()
  .catch(function(e) { throw e; });

第一个代码段将仅捕获最近的错误(其他错误将丢失),而第二个代码段将捕获链中任何地方的任何错误.

The first snippet will only catch errors on the latest then (the other errors will be lost) whereas the second snippet will catch any error anywhere along the chain.

但是我必须丢失一些东西,因为强迫用户记住在每个诺言之后做出的承诺都会违背诺言的目的.

But I must be missing something because forcing the user to remember putting a catch after every promise defeats the purpose of promises.

我误会并在最后放置 .catch()会在链中捕获任何错误吗?

Am I misunderstanding and placing a .catch() last will catch any error along the chain?

推荐答案

在第一种情况下,如果任何 then 处理程序抛出错误,则该错误将在最后一个 catch 处理程序.

In the first case, if any of the then handlers are throwing an error, then that error will be caught at the last catch handler.

在第二种情况下,如果任何 then 处理程序抛出错误,则该错误将转到最近的 catch 处理程序.当您在 catch 处理程序中抛出错误时,它也会转到下一个最近的 catch 处理程序.

In the second case, if any of the then handlers throw an error, that error will go to the nearest catch handler. As you throw the error in catch handlers as well, it will simply go to the next nearest catch handler.

我是否误解并在最后放置.catch()会在链中捕获任何错误?

Am I misunderstanding and placing a .catch() last will catch any error along the chain?

在大多数情况下,在承诺链末尾的

不, catch 是正确的选择.但是,如果您不希望由于中间失败而使整个承诺链失败,那么您可以返回 catch中的下一个 then 处理程序要使用的值.处理程序.

Nope, catch at the end of the promise chain is the right thing to do in most of the cases. But, in case if you don't want to fail the entire chain of promises because of an intermediate failure, then you can return the value to be used by the next then handler in the catch handler.

这篇关于如何正确捕捉承诺中的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆