Skip to content

Commit 431bfe1

Browse files
jasnellMylesBorins
authored andcommitted
doc: add note about multiple sync events and once
Fixes: #32431 PR-URL: #34220 Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Anto Aravinth <[email protected]> Reviewed-By: Trivikram Kamat <[email protected]>
1 parent ffe6886 commit 431bfe1

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

doc/api/events.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -892,6 +892,60 @@ ee.emit('error', new Error('boom'));
892892
// Prints: ok boom
893893
```
894894

895+
### Awaiting multiple events emitted on `process.nextTick()`
896+
897+
There is an edge case worth noting when using the `events.once()` function
898+
to await multiple events emitted on in the same batch of `process.nextTick()`
899+
operations, or whenever multiple events are emitted synchronously. Specifically,
900+
because the `process.nextTick()` queue is drained before the `Promise` microtask
901+
queue, and because `EventEmitter` emits all events synchronously, it is possible
902+
for `events.once()` to miss an event.
903+
904+
```js
905+
const { EventEmitter, once } = require('events');
906+
907+
const myEE = new EventEmitter();
908+
909+
async function foo() {
910+
await once(myEE, 'bar');
911+
console.log('bar');
912+
913+
// This Promise will never resolve because the 'foo' event will
914+
// have already been emitted before the Promise is created.
915+
await once(myEE, 'foo');
916+
console.log('foo');
917+
}
918+
919+
process.nextTick(() => {
920+
myEE.emit('bar');
921+
myEE.emit('foo');
922+
});
923+
924+
foo().then(() => console.log('done'));
925+
```
926+
927+
To catch both events, create each of the Promises *before* awaiting either
928+
of them, then it becomes possible to use `Promise.all()`, `Promise.race()`,
929+
or `Promise.allSettled()`:
930+
931+
```js
932+
const { EventEmitter, once } = require('events');
933+
934+
const myEE = new EventEmitter();
935+
936+
async function foo() {
937+
await Promise.all([once(myEE, 'bar'), once(myEE, 'foo')]);
938+
console.log('foo', 'bar');
939+
}
940+
941+
process.nextTick(() => {
942+
myEE.emit('bar');
943+
myEE.emit('foo');
944+
});
945+
946+
foo().then(() => console.log('done'));
947+
```
948+
895949
## `events.captureRejections`
896950
<!-- YAML
897951
added:

0 commit comments

Comments
 (0)