events.on(emitter, eventName[, options])


const { on, EventEmitter } = require('node:events');

(async () => {
  const ee = new EventEmitter();

  // 稍后触发
  process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
  });

  for await (const event of on(ee, 'foo')) {
    // 此内部块的执行是同步的,
    // 且每次处理一个事件(即使有等待)。
    // 如果需要并发执行,则不要使用。
    console.log(event); // 打印 ['bar'] [42]
  }
  // 此处无法到达
})();

返回迭代 eventName 事件的 AsyncIterator。 如果 EventEmitter 触发 'error',则将抛出错误。 它在退出循环时删除所有监听器。 每次迭代返回的 value 是由触发的事件参数组成的数组。

<AbortSignal> 可用于取消对事件的等待:

const { on, EventEmitter } = require('node:events');
const ac = new AbortController();

(async () => {
  const ee = new EventEmitter();

  // 稍后触发
  process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
  });

  for await (const event of on(ee, 'foo', { signal: ac.signal })) {
    // 此内部块的执行是同步的,
    // 且每次处理一个事件(即使有等待)。
    // 如果需要并发执行,则不要使用。
    console.log(event); // 打印 ['bar'] [42]
  }
  // 此处无法到达
})();

process.nextTick(() => ac.abort());
const { on, EventEmitter } = require('node:events');

(async () => {
  const ee = new EventEmitter();

  // Emit later on
  process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
  });

  for await (const event of on(ee, 'foo')) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
  }
  // Unreachable here
})();

Returns an AsyncIterator that iterates eventName events. It will throw if the EventEmitter emits 'error'. It removes all listeners when exiting the loop. The value returned by each iteration is an array composed of the emitted event arguments.

An <AbortSignal> can be used to cancel waiting on events:

const { on, EventEmitter } = require('node:events');
const ac = new AbortController();

(async () => {
  const ee = new EventEmitter();

  // Emit later on
  process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
  });

  for await (const event of on(ee, 'foo', { signal: ac.signal })) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
  }
  // Unreachable here
})();

process.nextTick(() => ac.abort());