事件:'rejectionHandled'


【Event: 'rejectionHandled'

  • promise <Promise> 已处理的未完成承诺。

'rejectionHandled' 事件会在 Promise 被拒绝后且在其上附加了错误处理器(例如使用 promise.catch())晚于 Node.js 事件循环的一个轮次时触发。

【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.】

Promise 对象之前可能会在 'unhandledRejection' 事件中被触发,但在处理过程中获得了一个拒绝处理器。

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

对于 Promise 链,没有一个所谓的顶层可以总是处理拒绝的概念。由于本质上是异步的,Promise 的拒绝可以在将来的某个时间点被处理,可能远晚于触发 'unhandledRejection' 事件所需的事件循环周期。

【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.】

换句话说,与同步代码中存在一个不断增长的未处理异常列表不同,在使用 Promise 时,未处理拒绝的列表可能会不断增减。

【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.】

在同步代码中,当未处理异常的列表增加时,会触发 'uncaughtException' 事件。

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

在异步代码中,当未处理拒绝的列表增长时,会触发 'unhandledRejection' 事件;当未处理拒绝的列表减少时,会触发 'rejectionHandled' 事件。

【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.】

import process from 'node:process';

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

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

在这个例子中,unhandledRejections Map 会随着时间的推移而增大和缩小,反映出那些最初未处理而随后被处理的拒绝情况。可以将这些错误记录到错误日志中,可以是定期记录(对于长时间运行的应用可能是最佳选择),也可以在进程退出时记录(对于脚本而言,这可能是最方便的)。

【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).】