'multipleResolves' 事件


  • type <string> 错误类型。'resolve''reject' 之一。
  • promise <Promise> 不止一次'resolve''reject'的 Promise。
  • value <any> 在原始解析后'resolve''reject'的 Promise 的值。

只要 Promise 有以下情况,就会触发 'multipleResolves' 事件:

  • resolve不止一次。
  • reject不止一次。
  • resolve后reject。
  • reject后resolve。

这对于在使用 Promise 构造函数时跟踪应用程序中的潜在错误非常有用,因为会以静默方式吞没多个解决。 但是,此事件的发生并不一定表示错误。 例如,Promise.race() 可以触发 'multipleResolves' 事件。

process.on('multipleResolves', (type, promise, reason) => {
  console.error(type, promise, reason);
  setImmediate(() => process.exit(1));
});

async function main() {
  try {
    return await new Promise((resolve, reject) => {
      resolve('第一次调用');
      resolve('吞没解决');
      reject(new Error('吞没解决'));
    });
  } catch {
    throw new Error('失败');
  }
}

main().then(console.log);
// resolve: Promise { '第一次调用' } '吞没解决'
// reject: Promise { '第一次调用' } Error: 吞没解决
//     at Promise (*)
//     at new Promise (<anonymous>)
//     at main (*)
// 第一次调用
  • type <string> The resolution type. One of 'resolve' or 'reject'.
  • promise <Promise> The promise that resolved or rejected more than once.
  • value <any> The value with which the promise was either resolved or rejected after the original resolve.

The 'multipleResolves' event is emitted whenever a Promise has been either:

  • Resolved more than once.
  • Rejected more than once.
  • Rejected after resolve.
  • Resolved after reject.

This is useful for tracking potential errors in an application while using the Promise constructor, as multiple resolutions are silently swallowed. However, the occurrence of this event does not necessarily indicate an error. For example, Promise.race() can trigger a 'multipleResolves' event.

process.on('multipleResolves', (type, promise, reason) => {
  console.error(type, promise, reason);
  setImmediate(() => process.exit(1));
});

async function main() {
  try {
    return await new Promise((resolve, reject) => {
      resolve('First call');
      resolve('Swallowed resolve');
      reject(new Error('Swallowed reject'));
    });
  } catch {
    throw new Error('Failed');
  }
}

main().then(console.log);
// resolve: Promise { 'First call' } 'Swallowed resolve'
// reject: Promise { 'First call' } Error: Swallowed reject
//     at Promise (*)
//     at new Promise (<anonymous>)
//     at main (*)
// First call