在Node.js 7中,什么是压缩UnhandledPromiseRejectionWarning的正确方法? [英] In Node.js 7 what is the proper way to suppress UnhandledPromiseRejectionWarning?

查看:83
本文介绍了在Node.js 7中,什么是压缩UnhandledPromiseRejectionWarning的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Node.js中,我有一个只包含一个函数的模块。该函数返回promise并且可以拒绝promise。我仍然不想强制模块的所有用户明确地处理拒绝。在某些情况下,通过设计,忽略返回的promise是有意义的。此外,我不希望能够处理远离模块用户的承诺拒绝。

In Node.js I have a module which consists of just one function. The function returns promise and the promise could be rejected. Still I don't want to force all users of the module to handle the rejection explicitly. By design in some cases it makes sense to just ignore the returned promise. Also I don't want to take the ability to handle the promise rejection away from module users.

正确执行此操作的方法是什么?

What is the way to properly do so?

升级到Node.js 7.1.0后,忽略拒绝处理的所有单元测试都显示以下警告:

After upgrading to Node.js 7.1.0 all my unit tests which ignore rejection handling show the following warning:

(node:12732) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: try to throw an error from unit test
(node:12732) 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.

在<$ c中提到的将来阻止终止Node.js进程的正确方法是什么$ c> DeprecationWarning description?

What is the proper way to prevent termination of Node.js process in the future mentioned in DeprecationWarning description?

推荐答案

一般情况下,使用像bluebird这样的自定义库你可以抑制拒绝只是来自您的代码,但没有其他地方。原生承诺还不能做到这一点。

In general, using a custom library like bluebird you can suppress rejections just from your code but nowhere else. Native promises can't do this yet.

但是你可以通过为它添加一个catch处理程序来手动抑制一个承诺。

You can however manually suppress a promise by adding a catch handler for it.

 function yourExportedFunction() {
     const p = promiseThatMightRejectFn(); 
     p.catch(() => {}); // add an empty catch handler
     return p;
 }

这样你明确地忽略拒绝来自承诺所以它不再是一个未经处理的拒绝只是一个被压制的拒绝。

This way you are explicitly ignoring the rejection from the promise so it is no longer an unhandled rejection just a suppressed one.

这篇关于在Node.js 7中,什么是压缩UnhandledPromiseRejectionWarning的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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