如果承诺被拒绝,如何正确抛出错误? (UnhandledPromiseRejectionWarning) [英] how to properly throw an error if promise is rejected? (UnhandledPromiseRejectionWarning)

查看:1566
本文介绍了如果承诺被拒绝,如何正确抛出错误? (UnhandledPromiseRejectionWarning)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个承诺,如果承诺被拒绝,我希望抛出异常。我试过这个:

I have a promise and I would like an exception to be thrown if the promise is rejected. I tried this:

var p = new Promise( (resolve, reject) => {
  reject ("Error!");
} );

p.then(value => {console.log(value);});

但是我得到了折旧警告:

but I get a DeprecationWarning:

(node:44056) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error!
(node:44056) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

抛出错误的正确方法是什么(以便程序以堆栈跟踪终止)如果承诺被拒绝了?

What is the correct way to throw an error (so that the program is terminated with a stack trace) if the promise is rejected?

我已经尝试在catch子句中插入一个throw语句,但这会再次产生DeprecationWarning。实际上(在一些阅读之后)我理解,抛出一个catch会产生对拒绝回调的另一个调用。

I already tried to insert a throw statement in a catch clause, but this again produces a DeprecationWarning as before. In fact (after some reading) I understand that a throw in a catch produce another call to the reject callback.

推荐答案

你可以捕获 unhandledRejection 事件以记录您使用正确的错误拒绝的堆栈跟踪提供

You can catch unhandledRejection events to log an stack trace, provided that you reject using a proper Error:

var p = new Promise( (resolve, reject) => {
  reject( Error("Error!") );
} );

p.then(value => {console.log(value);});

process.on('unhandledRejection', e => {
  console.error(e);
});

这篇关于如果承诺被拒绝,如何正确抛出错误? (UnhandledPromiseRejectionWarning)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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