当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Node.js events.on(emitter, eventName[, options])用法及代码示例

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

添加于:v13.6.0、v12.16.0

参数
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
})();

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

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

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());

相关用法


注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品 events.on(emitter, eventName[, options])。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。