'rejectionHandled' 事件


  • promise <Promise> 最近处理的 promise。

如果有 Promise 被 rejected,并且此 Promise在 Node.js 事件循环的下次轮询及之后期间,被绑定了一个错误处理器(例如使用 promise.catch()),会触发 'rejectionHandled' 事件。

此事件监听器的回调函数使用 rejected 的 Promise 引用,作为唯一入参。

Promise 对象应该已经在 'unhandledRejection' 事件触发时被处理,但是在被处理过程中获得了一个 rejection 处理器。

对于 Promise 链,没有概念表明在 Promise 链的哪个地方,所有的 rejection 总是会被处理。 由于本来就是异步的,一个 Promise rejection 可以在将来的某个时间点被处理-可能要远远晚于 'unhandledRejection' 事件被触发及处理的时间。

另一种表述的方式就是,与使用同步代码时会出现不断增长的未处理异常列表不同,使用 Promise 时,未处理异常列表可能会出现增长然后收缩的情况。

在同步代码情况下,当未处理异常列表增长时,会触发 'uncaughtException' 事件。

在异步代码情况下,当未处理异常列表增长时,会触发 'unhandledRejection' 事件,当未处理列表收缩时,会触发 'rejectionHandled' 事件。

const unhandledRejections = new Map();
process.on('unhandledRejection', (reason, promise) => {
  unhandledRejections.set(promise, reason);
});
process.on('rejectionHandled', (promise) => {
  unhandledRejections.delete(promise);
});

在上述例子中,unhandledRejections 会随着时间增加和缩减,表明 rejection 开始是未被处理状态,然后变成已处理状态。 可以定时(对于需长期运行的应用,这个可能是最好的方式)或当进程结束时(对脚本的应用可能是最方便的),在错误日志中记录这些错误信息。

  • promise <Promise> The late handled promise.

The 'rejectionHandled' event is emitted whenever a Promise has been rejected and an error handler was attached to it (using promise.catch(), for example) later than one turn of the Node.js event loop.

The Promise object would have previously been emitted in an 'unhandledRejection' event, but during the course of processing gained a rejection handler.

There is no notion of a top level for a Promise chain at which rejections can always be handled. Being inherently asynchronous in nature, a Promise rejection can be handled at a future point in time — possibly much later than the event loop turn it takes for the 'unhandledRejection' event to be emitted.

Another way of stating this is that, unlike in synchronous code where there is an ever-growing list of unhandled exceptions, with Promises there can be a growing-and-shrinking list of unhandled rejections.

In synchronous code, the 'uncaughtException' event is emitted when the list of unhandled exceptions grows.

In asynchronous code, the 'unhandledRejection' event is emitted when the list of unhandled rejections grows, and the 'rejectionHandled' event is emitted when the list of unhandled rejections shrinks.

const unhandledRejections = new Map();
process.on('unhandledRejection', (reason, promise) => {
  unhandledRejections.set(promise, reason);
});
process.on('rejectionHandled', (promise) => {
  unhandledRejections.delete(promise);
});

In this example, the unhandledRejections Map will grow and shrink over time, reflecting rejections that start unhandled and then become handled. It is possible to record such errors in an error log, either periodically (which is likely best for long-running application) or upon process exit (which is likely most convenient for scripts).