@@ -892,6 +892,60 @@ ee.emit('error', new Error('boom'));
892
892
// Prints: ok boom
893
893
```
894
894
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
+
895
949
## ` events.captureRejections `
896
950
<!-- YAML
897
951
added:
0 commit comments