events.on(emitter, eventName[, options])
-
emitter
<EventEmitter> -
eventName
<string> | <symbol> 正在监听的事件的名称¥
eventName
<string> | <symbol> The name of the event being listened for -
options
<Object>-
signal
<AbortSignal> 可用于取消等待事件。¥
signal
<AbortSignal> Can be used to cancel awaiting events.
-
-
返回:<AsyncIterator> 迭代
emitter
触发的eventName
事件¥Returns: <AsyncIterator> that iterates
eventName
events emitted by theemitter
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
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
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
是由触发的事件参数组成的数组。
¥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.
<AbortSignal> 可用于取消对事件的等待:
¥An <AbortSignal> can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
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());
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());