在Node.js 7中,抑制UnhandledPromiseRejectionWarning的正确方法是什么?

在Node.js中,我有一个由一个函数组成的模块。 函数返回promise,promise可能被拒绝。 我仍然不想强制模块的所有用户明确地处理拒绝。 通过devise在某些情况下,忽略返回的承诺是有意义的。 此外,我不想承担模块用户的承诺拒绝的能力。

什么是正确的做法呢?

升级到Node.js 7.1.0之后,我所有忽略拒绝处理的unit testing都显示如下警告:

(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. 

DeprecationWarning描述中提到将来终止Node.js过程的正确方法是什么?

一般来说,使用像蓝鸟一样的自定义库,你可以抑制从你的代码拒绝,但其他地方。 原生承诺不能做到这一点呢。

但是,您可以通过为其添加捕获处理程序来手动取消承诺。

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

这样,你明确地忽略了承诺的拒绝,所以它不再是一个被压制的拒绝。

如果您担心未处理的拒绝会导致您的Nodejs进程在将来无意中终止,则可以为process对象上的“unhandledRejection”事件注册一个事件处理程序。

 process.on('unhandledRejection', (err, p) => { console.log('An unhandledRejection occurred'); console.log(`Rejected Promise: ${p}`); console.log(`Rejection: ${err}`); }); 

编辑

如果您希望模块的实现用户决定是否处理代码中的错误,则应该将您的承诺还给调用者。

yourModule.js

 function increment(value) { return new Promise((resolve, reject) => { if (!value) return reject(new Error('a value to increment is required')); return resolve(value++); }); } 

theirModule.js

 const increment = require('./yourModule.js'); increment() .then((incremented) => { console.log(`Value incremented to ${incremented}`); }) .catch((err) => { // Handle rejections returned from increment() console.log(err); }); 

这不是你要解决的问题。

只要按照预期的方式使用承诺。 如果最终用户不想处理所有拒绝,那么他们必须添加一个unhandledRejection拒绝unhandledRejection程序。 否则,他们将需要添加捕获。

如果你的错误真的没有突破,那么你不应该拒绝他们。 只需解决一个错误值。 例如:

成功: resolve({result, error:null})

失败: resolve({result:null, error})

拒绝并离开最终用户决定如何处理它还是更好的。

我无法想出任何方法去做你所描述的事情。

如果您不关心将错误传递给用户,则可以在承诺链的末尾添加一个虚拟catch块:

 Promise.reject('foo') .catch(() => {}) 

这会使警告消失,但不会让用户处理错误。

也许你可以添加一个选项,用户可以决定是否要处理错误。