'multipleResolves' 事件


  • type <string> 解决类型 'resolve''reject' 之一。
  • promise <Promise> 不止一次解决或拒绝的 promise。
  • value <any> 在原始解决之后解决或拒绝 promise 的值。

每当 Promise 满足以下任一条件时,就会触发 'multipleResolves' 事件:

  • 解决了不止一次。
  • 拒绝了不止一次。
  • 解决后拒绝。
  • 拒绝后解决。

这对于在使用 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('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
  • 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