1# Events 2 3<!--introduced_in=v0.10.0--> 4 5> Stability: 2 - Stable 6 7<!--type=module--> 8 9<!-- source_link=lib/events.js --> 10 11Much of the Node.js core API is built around an idiomatic asynchronous 12event-driven architecture in which certain kinds of objects (called "emitters") 13emit named events that cause `Function` objects ("listeners") to be called. 14 15For instance: a [`net.Server`][] object emits an event each time a peer 16connects to it; a [`fs.ReadStream`][] emits an event when the file is opened; 17a [stream][] emits an event whenever data is available to be read. 18 19All objects that emit events are instances of the `EventEmitter` class. These 20objects expose an `eventEmitter.on()` function that allows one or more 21functions to be attached to named events emitted by the object. Typically, 22event names are camel-cased strings but any valid JavaScript property key 23can be used. 24 25When the `EventEmitter` object emits an event, all of the functions attached 26to that specific event are called _synchronously_. Any values returned by the 27called listeners are _ignored_ and will be discarded. 28 29The following example shows a simple `EventEmitter` instance with a single 30listener. The `eventEmitter.on()` method is used to register listeners, while 31the `eventEmitter.emit()` method is used to trigger the event. 32 33```js 34const EventEmitter = require('events'); 35 36class MyEmitter extends EventEmitter {} 37 38const myEmitter = new MyEmitter(); 39myEmitter.on('event', () => { 40 console.log('an event occurred!'); 41}); 42myEmitter.emit('event'); 43``` 44 45## Passing arguments and `this` to listeners 46 47The `eventEmitter.emit()` method allows an arbitrary set of arguments to be 48passed to the listener functions. Keep in mind that when 49an ordinary listener function is called, the standard `this` keyword 50is intentionally set to reference the `EventEmitter` instance to which the 51listener is attached. 52 53```js 54const myEmitter = new MyEmitter(); 55myEmitter.on('event', function(a, b) { 56 console.log(a, b, this, this === myEmitter); 57 // Prints: 58 // a b MyEmitter { 59 // domain: null, 60 // _events: { event: [Function] }, 61 // _eventsCount: 1, 62 // _maxListeners: undefined } true 63}); 64myEmitter.emit('event', 'a', 'b'); 65``` 66 67It is possible to use ES6 Arrow Functions as listeners, however, when doing so, 68the `this` keyword will no longer reference the `EventEmitter` instance: 69 70```js 71const myEmitter = new MyEmitter(); 72myEmitter.on('event', (a, b) => { 73 console.log(a, b, this); 74 // Prints: a b {} 75}); 76myEmitter.emit('event', 'a', 'b'); 77``` 78 79## Asynchronous vs. synchronous 80 81The `EventEmitter` calls all listeners synchronously in the order in which 82they were registered. This ensures the proper sequencing of 83events and helps avoid race conditions and logic errors. When appropriate, 84listener functions can switch to an asynchronous mode of operation using 85the `setImmediate()` or `process.nextTick()` methods: 86 87```js 88const myEmitter = new MyEmitter(); 89myEmitter.on('event', (a, b) => { 90 setImmediate(() => { 91 console.log('this happens asynchronously'); 92 }); 93}); 94myEmitter.emit('event', 'a', 'b'); 95``` 96 97## Handling events only once 98 99When a listener is registered using the `eventEmitter.on()` method, that 100listener will be invoked _every time_ the named event is emitted. 101 102```js 103const myEmitter = new MyEmitter(); 104let m = 0; 105myEmitter.on('event', () => { 106 console.log(++m); 107}); 108myEmitter.emit('event'); 109// Prints: 1 110myEmitter.emit('event'); 111// Prints: 2 112``` 113 114Using the `eventEmitter.once()` method, it is possible to register a listener 115that is called at most once for a particular event. Once the event is emitted, 116the listener is unregistered and *then* called. 117 118```js 119const myEmitter = new MyEmitter(); 120let m = 0; 121myEmitter.once('event', () => { 122 console.log(++m); 123}); 124myEmitter.emit('event'); 125// Prints: 1 126myEmitter.emit('event'); 127// Ignored 128``` 129 130## Error events 131 132When an error occurs within an `EventEmitter` instance, the typical action is 133for an `'error'` event to be emitted. These are treated as special cases 134within Node.js. 135 136If an `EventEmitter` does _not_ have at least one listener registered for the 137`'error'` event, and an `'error'` event is emitted, the error is thrown, a 138stack trace is printed, and the Node.js process exits. 139 140```js 141const myEmitter = new MyEmitter(); 142myEmitter.emit('error', new Error('whoops!')); 143// Throws and crashes Node.js 144``` 145 146To guard against crashing the Node.js process the [`domain`][] module can be 147used. (Note, however, that the `domain` module is deprecated.) 148 149As a best practice, listeners should always be added for the `'error'` events. 150 151```js 152const myEmitter = new MyEmitter(); 153myEmitter.on('error', (err) => { 154 console.error('whoops! there was an error'); 155}); 156myEmitter.emit('error', new Error('whoops!')); 157// Prints: whoops! there was an error 158``` 159 160It is possible to monitor `'error'` events without consuming the emitted error 161by installing a listener using the symbol `errorMonitor`. 162 163```js 164const myEmitter = new MyEmitter(); 165myEmitter.on(EventEmitter.errorMonitor, (err) => { 166 MyMonitoringTool.log(err); 167}); 168myEmitter.emit('error', new Error('whoops!')); 169// Still throws and crashes Node.js 170``` 171 172## Capture rejections of promises 173 174> Stability: 1 - captureRejections is experimental. 175 176Using `async` functions with event handlers is problematic, because it 177can lead to an unhandled rejection in case of a thrown exception: 178 179```js 180const ee = new EventEmitter(); 181ee.on('something', async (value) => { 182 throw new Error('kaboom'); 183}); 184``` 185 186The `captureRejections` option in the `EventEmitter` constructor or the global 187setting change this behavior, installing a `.then(undefined, handler)` 188handler on the `Promise`. This handler routes the exception 189asynchronously to the [`Symbol.for('nodejs.rejection')`][rejection] method 190if there is one, or to [`'error'`][error] event handler if there is none. 191 192```js 193const ee1 = new EventEmitter({ captureRejections: true }); 194ee1.on('something', async (value) => { 195 throw new Error('kaboom'); 196}); 197 198ee1.on('error', console.log); 199 200const ee2 = new EventEmitter({ captureRejections: true }); 201ee2.on('something', async (value) => { 202 throw new Error('kaboom'); 203}); 204 205ee2[Symbol.for('nodejs.rejection')] = console.log; 206``` 207 208Setting `EventEmitter.captureRejections = true` will change the default for all 209new instances of `EventEmitter`. 210 211```js 212EventEmitter.captureRejections = true; 213const ee1 = new EventEmitter(); 214ee1.on('something', async (value) => { 215 throw new Error('kaboom'); 216}); 217 218ee1.on('error', console.log); 219``` 220 221The `'error'` events that are generated by the `captureRejections` behavior 222do not have a catch handler to avoid infinite error loops: the 223recommendation is to **not use `async` functions as `'error'` event handlers**. 224 225## Class: `EventEmitter` 226<!-- YAML 227added: v0.1.26 228changes: 229 - version: v12.16.0 230 pr-url: https://github.com/nodejs/node/pull/27867 231 description: Added captureRejections option. 232--> 233 234The `EventEmitter` class is defined and exposed by the `events` module: 235 236```js 237const EventEmitter = require('events'); 238``` 239 240All `EventEmitter`s emit the event `'newListener'` when new listeners are 241added and `'removeListener'` when existing listeners are removed. 242 243It supports the following option: 244 245* `captureRejections` {boolean} It enables 246 [automatic capturing of promise rejection][capturerejections]. 247 Default: `false`. 248 249### Event: 'newListener' 250<!-- YAML 251added: v0.1.26 252--> 253 254* `eventName` {string|symbol} The name of the event being listened for 255* `listener` {Function} The event handler function 256 257The `EventEmitter` instance will emit its own `'newListener'` event *before* 258a listener is added to its internal array of listeners. 259 260Listeners registered for the `'newListener'` event will be passed the event 261name and a reference to the listener being added. 262 263The fact that the event is triggered before adding the listener has a subtle 264but important side effect: any *additional* listeners registered to the same 265`name` *within* the `'newListener'` callback will be inserted *before* the 266listener that is in the process of being added. 267 268```js 269const myEmitter = new MyEmitter(); 270// Only do this once so we don't loop forever 271myEmitter.once('newListener', (event, listener) => { 272 if (event === 'event') { 273 // Insert a new listener in front 274 myEmitter.on('event', () => { 275 console.log('B'); 276 }); 277 } 278}); 279myEmitter.on('event', () => { 280 console.log('A'); 281}); 282myEmitter.emit('event'); 283// Prints: 284// B 285// A 286``` 287 288### Event: `'removeListener'` 289<!-- YAML 290added: v0.9.3 291changes: 292 - version: v6.1.0, v4.7.0 293 pr-url: https://github.com/nodejs/node/pull/6394 294 description: For listeners attached using `.once()`, the `listener` argument 295 now yields the original listener function. 296--> 297 298* `eventName` {string|symbol} The event name 299* `listener` {Function} The event handler function 300 301The `'removeListener'` event is emitted *after* the `listener` is removed. 302 303### `EventEmitter.listenerCount(emitter, eventName)` 304<!-- YAML 305added: v0.9.12 306deprecated: v3.2.0 307--> 308 309> Stability: 0 - Deprecated: Use [`emitter.listenerCount()`][] instead. 310 311* `emitter` {EventEmitter} The emitter to query 312* `eventName` {string|symbol} The event name 313 314A class method that returns the number of listeners for the given `eventName` 315registered on the given `emitter`. 316 317```js 318const myEmitter = new MyEmitter(); 319myEmitter.on('event', () => {}); 320myEmitter.on('event', () => {}); 321console.log(EventEmitter.listenerCount(myEmitter, 'event')); 322// Prints: 2 323``` 324 325### `EventEmitter.defaultMaxListeners` 326<!-- YAML 327added: v0.11.2 328--> 329 330By default, a maximum of `10` listeners can be registered for any single 331event. This limit can be changed for individual `EventEmitter` instances 332using the [`emitter.setMaxListeners(n)`][] method. To change the default 333for *all* `EventEmitter` instances, the `EventEmitter.defaultMaxListeners` 334property can be used. If this value is not a positive number, a `TypeError` 335will be thrown. 336 337Take caution when setting the `EventEmitter.defaultMaxListeners` because the 338change affects *all* `EventEmitter` instances, including those created before 339the change is made. However, calling [`emitter.setMaxListeners(n)`][] still has 340precedence over `EventEmitter.defaultMaxListeners`. 341 342This is not a hard limit. The `EventEmitter` instance will allow 343more listeners to be added but will output a trace warning to stderr indicating 344that a "possible EventEmitter memory leak" has been detected. For any single 345`EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` 346methods can be used to temporarily avoid this warning: 347 348```js 349emitter.setMaxListeners(emitter.getMaxListeners() + 1); 350emitter.once('event', () => { 351 // do stuff 352 emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); 353}); 354``` 355 356The [`--trace-warnings`][] command line flag can be used to display the 357stack trace for such warnings. 358 359The emitted warning can be inspected with [`process.on('warning')`][] and will 360have the additional `emitter`, `type` and `count` properties, referring to 361the event emitter instance, the event’s name and the number of attached 362listeners, respectively. 363Its `name` property is set to `'MaxListenersExceededWarning'`. 364 365### `EventEmitter.errorMonitor` 366<!-- YAML 367added: v12.17.0 368--> 369 370This symbol shall be used to install a listener for only monitoring `'error'` 371events. Listeners installed using this symbol are called before the regular 372`'error'` listeners are called. 373 374Installing a listener using this symbol does not change the behavior once an 375`'error'` event is emitted, therefore the process will still crash if no 376regular `'error'` listener is installed. 377 378### `emitter.addListener(eventName, listener)` 379<!-- YAML 380added: v0.1.26 381--> 382 383* `eventName` {string|symbol} 384* `listener` {Function} 385 386Alias for `emitter.on(eventName, listener)`. 387 388### `emitter.emit(eventName[, ...args])` 389<!-- YAML 390added: v0.1.26 391--> 392 393* `eventName` {string|symbol} 394* `...args` {any} 395* Returns: {boolean} 396 397Synchronously calls each of the listeners registered for the event named 398`eventName`, in the order they were registered, passing the supplied arguments 399to each. 400 401Returns `true` if the event had listeners, `false` otherwise. 402 403```js 404const EventEmitter = require('events'); 405const myEmitter = new EventEmitter(); 406 407// First listener 408myEmitter.on('event', function firstListener() { 409 console.log('Helloooo! first listener'); 410}); 411// Second listener 412myEmitter.on('event', function secondListener(arg1, arg2) { 413 console.log(`event with parameters ${arg1}, ${arg2} in second listener`); 414}); 415// Third listener 416myEmitter.on('event', function thirdListener(...args) { 417 const parameters = args.join(', '); 418 console.log(`event with parameters ${parameters} in third listener`); 419}); 420 421console.log(myEmitter.listeners('event')); 422 423myEmitter.emit('event', 1, 2, 3, 4, 5); 424 425// Prints: 426// [ 427// [Function: firstListener], 428// [Function: secondListener], 429// [Function: thirdListener] 430// ] 431// Helloooo! first listener 432// event with parameters 1, 2 in second listener 433// event with parameters 1, 2, 3, 4, 5 in third listener 434``` 435 436### `emitter.eventNames()` 437<!-- YAML 438added: v6.0.0 439--> 440 441* Returns: {Array} 442 443Returns an array listing the events for which the emitter has registered 444listeners. The values in the array will be strings or `Symbol`s. 445 446```js 447const EventEmitter = require('events'); 448const myEE = new EventEmitter(); 449myEE.on('foo', () => {}); 450myEE.on('bar', () => {}); 451 452const sym = Symbol('symbol'); 453myEE.on(sym, () => {}); 454 455console.log(myEE.eventNames()); 456// Prints: [ 'foo', 'bar', Symbol(symbol) ] 457``` 458 459### `emitter.getMaxListeners()` 460<!-- YAML 461added: v1.0.0 462--> 463 464* Returns: {integer} 465 466Returns the current max listener value for the `EventEmitter` which is either 467set by [`emitter.setMaxListeners(n)`][] or defaults to 468[`EventEmitter.defaultMaxListeners`][]. 469 470### `emitter.listenerCount(eventName)` 471<!-- YAML 472added: v3.2.0 473--> 474 475* `eventName` {string|symbol} The name of the event being listened for 476* Returns: {integer} 477 478Returns the number of listeners listening to the event named `eventName`. 479 480### `emitter.listeners(eventName)` 481<!-- YAML 482added: v0.1.26 483changes: 484 - version: v7.0.0 485 pr-url: https://github.com/nodejs/node/pull/6881 486 description: For listeners attached using `.once()` this returns the 487 original listeners instead of wrapper functions now. 488--> 489 490* `eventName` {string|symbol} 491* Returns: {Function[]} 492 493Returns a copy of the array of listeners for the event named `eventName`. 494 495```js 496server.on('connection', (stream) => { 497 console.log('someone connected!'); 498}); 499console.log(util.inspect(server.listeners('connection'))); 500// Prints: [ [Function] ] 501``` 502 503### `emitter.off(eventName, listener)` 504<!-- YAML 505added: v10.0.0 506--> 507 508* `eventName` {string|symbol} 509* `listener` {Function} 510* Returns: {EventEmitter} 511 512Alias for [`emitter.removeListener()`][]. 513 514### `emitter.on(eventName, listener)` 515<!-- YAML 516added: v0.1.101 517--> 518 519* `eventName` {string|symbol} The name of the event. 520* `listener` {Function} The callback function 521* Returns: {EventEmitter} 522 523Adds the `listener` function to the end of the listeners array for the 524event named `eventName`. No checks are made to see if the `listener` has 525already been added. Multiple calls passing the same combination of `eventName` 526and `listener` will result in the `listener` being added, and called, multiple 527times. 528 529```js 530server.on('connection', (stream) => { 531 console.log('someone connected!'); 532}); 533``` 534 535Returns a reference to the `EventEmitter`, so that calls can be chained. 536 537By default, event listeners are invoked in the order they are added. The 538`emitter.prependListener()` method can be used as an alternative to add the 539event listener to the beginning of the listeners array. 540 541```js 542const myEE = new EventEmitter(); 543myEE.on('foo', () => console.log('a')); 544myEE.prependListener('foo', () => console.log('b')); 545myEE.emit('foo'); 546// Prints: 547// b 548// a 549``` 550 551### `emitter.once(eventName, listener)` 552<!-- YAML 553added: v0.3.0 554--> 555 556* `eventName` {string|symbol} The name of the event. 557* `listener` {Function} The callback function 558* Returns: {EventEmitter} 559 560Adds a **one-time** `listener` function for the event named `eventName`. The 561next time `eventName` is triggered, this listener is removed and then invoked. 562 563```js 564server.once('connection', (stream) => { 565 console.log('Ah, we have our first user!'); 566}); 567``` 568 569Returns a reference to the `EventEmitter`, so that calls can be chained. 570 571By default, event listeners are invoked in the order they are added. The 572`emitter.prependOnceListener()` method can be used as an alternative to add the 573event listener to the beginning of the listeners array. 574 575```js 576const myEE = new EventEmitter(); 577myEE.once('foo', () => console.log('a')); 578myEE.prependOnceListener('foo', () => console.log('b')); 579myEE.emit('foo'); 580// Prints: 581// b 582// a 583``` 584 585### `emitter.prependListener(eventName, listener)` 586<!-- YAML 587added: v6.0.0 588--> 589 590* `eventName` {string|symbol} The name of the event. 591* `listener` {Function} The callback function 592* Returns: {EventEmitter} 593 594Adds the `listener` function to the *beginning* of the listeners array for the 595event named `eventName`. No checks are made to see if the `listener` has 596already been added. Multiple calls passing the same combination of `eventName` 597and `listener` will result in the `listener` being added, and called, multiple 598times. 599 600```js 601server.prependListener('connection', (stream) => { 602 console.log('someone connected!'); 603}); 604``` 605 606Returns a reference to the `EventEmitter`, so that calls can be chained. 607 608### `emitter.prependOnceListener(eventName, listener)` 609<!-- YAML 610added: v6.0.0 611--> 612 613* `eventName` {string|symbol} The name of the event. 614* `listener` {Function} The callback function 615* Returns: {EventEmitter} 616 617Adds a **one-time** `listener` function for the event named `eventName` to the 618*beginning* of the listeners array. The next time `eventName` is triggered, this 619listener is removed, and then invoked. 620 621```js 622server.prependOnceListener('connection', (stream) => { 623 console.log('Ah, we have our first user!'); 624}); 625``` 626 627Returns a reference to the `EventEmitter`, so that calls can be chained. 628 629### `emitter.removeAllListeners([eventName])` 630<!-- YAML 631added: v0.1.26 632--> 633 634* `eventName` {string|symbol} 635* Returns: {EventEmitter} 636 637Removes all listeners, or those of the specified `eventName`. 638 639It is bad practice to remove listeners added elsewhere in the code, 640particularly when the `EventEmitter` instance was created by some other 641component or module (e.g. sockets or file streams). 642 643Returns a reference to the `EventEmitter`, so that calls can be chained. 644 645### `emitter.removeListener(eventName, listener)` 646<!-- YAML 647added: v0.1.26 648--> 649 650* `eventName` {string|symbol} 651* `listener` {Function} 652* Returns: {EventEmitter} 653 654Removes the specified `listener` from the listener array for the event named 655`eventName`. 656 657```js 658const callback = (stream) => { 659 console.log('someone connected!'); 660}; 661server.on('connection', callback); 662// ... 663server.removeListener('connection', callback); 664``` 665 666`removeListener()` will remove, at most, one instance of a listener from the 667listener array. If any single listener has been added multiple times to the 668listener array for the specified `eventName`, then `removeListener()` must be 669called multiple times to remove each instance. 670 671Once an event has been emitted, all listeners attached to it at the 672time of emitting will be called in order. This implies that any 673`removeListener()` or `removeAllListeners()` calls *after* emitting and 674*before* the last listener finishes execution will not remove them from 675`emit()` in progress. Subsequent events will behave as expected. 676 677```js 678const myEmitter = new MyEmitter(); 679 680const callbackA = () => { 681 console.log('A'); 682 myEmitter.removeListener('event', callbackB); 683}; 684 685const callbackB = () => { 686 console.log('B'); 687}; 688 689myEmitter.on('event', callbackA); 690 691myEmitter.on('event', callbackB); 692 693// callbackA removes listener callbackB but it will still be called. 694// Internal listener array at time of emit [callbackA, callbackB] 695myEmitter.emit('event'); 696// Prints: 697// A 698// B 699 700// callbackB is now removed. 701// Internal listener array [callbackA] 702myEmitter.emit('event'); 703// Prints: 704// A 705``` 706 707Because listeners are managed using an internal array, calling this will 708change the position indices of any listener registered *after* the listener 709being removed. This will not impact the order in which listeners are called, 710but it means that any copies of the listener array as returned by 711the `emitter.listeners()` method will need to be recreated. 712 713When a single function has been added as a handler multiple times for a single 714event (as in the example below), `removeListener()` will remove the most 715recently added instance. In the example the `once('ping')` 716listener is removed: 717 718```js 719const ee = new EventEmitter(); 720 721function pong() { 722 console.log('pong'); 723} 724 725ee.on('ping', pong); 726ee.once('ping', pong); 727ee.removeListener('ping', pong); 728 729ee.emit('ping'); 730ee.emit('ping'); 731``` 732 733Returns a reference to the `EventEmitter`, so that calls can be chained. 734 735### `emitter.setMaxListeners(n)` 736<!-- YAML 737added: v0.3.5 738--> 739 740* `n` {integer} 741* Returns: {EventEmitter} 742 743By default `EventEmitter`s will print a warning if more than `10` listeners are 744added for a particular event. This is a useful default that helps finding 745memory leaks. The `emitter.setMaxListeners()` method allows the limit to be 746modified for this specific `EventEmitter` instance. The value can be set to 747`Infinity` (or `0`) to indicate an unlimited number of listeners. 748 749Returns a reference to the `EventEmitter`, so that calls can be chained. 750 751### `emitter.rawListeners(eventName)` 752<!-- YAML 753added: v9.4.0 754--> 755 756* `eventName` {string|symbol} 757* Returns: {Function[]} 758 759Returns a copy of the array of listeners for the event named `eventName`, 760including any wrappers (such as those created by `.once()`). 761 762```js 763const emitter = new EventEmitter(); 764emitter.once('log', () => console.log('log once')); 765 766// Returns a new Array with a function `onceWrapper` which has a property 767// `listener` which contains the original listener bound above 768const listeners = emitter.rawListeners('log'); 769const logFnWrapper = listeners[0]; 770 771// Logs "log once" to the console and does not unbind the `once` event 772logFnWrapper.listener(); 773 774// Logs "log once" to the console and removes the listener 775logFnWrapper(); 776 777emitter.on('log', () => console.log('log persistently')); 778// Will return a new Array with a single function bound by `.on()` above 779const newListeners = emitter.rawListeners('log'); 780 781// Logs "log persistently" twice 782newListeners[0](); 783emitter.emit('log'); 784``` 785 786### `emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])` 787<!-- YAML 788added: v12.16.0 789--> 790 791> Stability: 1 - captureRejections is experimental. 792 793* `err` Error 794* `eventName` {string|symbol} 795* `...args` {any} 796 797The `Symbol.for('nodejs.rejection')` method is called in case a 798promise rejection happens when emitting an event and 799[`captureRejections`][capturerejections] is enabled on the emitter. 800It is possible to use [`events.captureRejectionSymbol`][rejectionsymbol] in 801place of `Symbol.for('nodejs.rejection')`. 802 803```js 804const { EventEmitter, captureRejectionSymbol } = require('events'); 805 806class MyClass extends EventEmitter { 807 constructor() { 808 super({ captureRejections: true }); 809 } 810 811 [captureRejectionSymbol](err, event, ...args) { 812 console.log('rejection happened for', event, 'with', err, ...args); 813 this.destroy(err); 814 } 815 816 destroy(err) { 817 // Tear the resource down here. 818 } 819} 820``` 821 822## `events.once(emitter, name)` 823<!-- YAML 824added: v11.13.0 825--> 826 827* `emitter` {EventEmitter} 828* `name` {string} 829* Returns: {Promise} 830 831Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given 832event or that is rejected if the `EventEmitter` emits `'error'` while waiting. 833The `Promise` will resolve with an array of all the arguments emitted to the 834given event. 835 836This method is intentionally generic and works with the web platform 837[EventTarget][WHATWG-EventTarget] interface, which has no special 838`'error'` event semantics and does not listen to the `'error'` event. 839 840```js 841const { once, EventEmitter } = require('events'); 842 843async function run() { 844 const ee = new EventEmitter(); 845 846 process.nextTick(() => { 847 ee.emit('myevent', 42); 848 }); 849 850 const [value] = await once(ee, 'myevent'); 851 console.log(value); 852 853 const err = new Error('kaboom'); 854 process.nextTick(() => { 855 ee.emit('error', err); 856 }); 857 858 try { 859 await once(ee, 'myevent'); 860 } catch (err) { 861 console.log('error happened', err); 862 } 863} 864 865run(); 866``` 867 868The special handling of the `'error'` event is only used when `events.once()` 869is used to wait for another event. If `events.once()` is used to wait for the 870'`error'` event itself, then it is treated as any other kind of event without 871special handling: 872 873```js 874const { EventEmitter, once } = require('events'); 875 876const ee = new EventEmitter(); 877 878once(ee, 'error') 879 .then(([err]) => console.log('ok', err.message)) 880 .catch((err) => console.log('error', err.message)); 881 882ee.emit('error', new Error('boom')); 883 884// Prints: ok boom 885``` 886 887### Awaiting multiple events emitted on `process.nextTick()` 888 889There is an edge case worth noting when using the `events.once()` function 890to await multiple events emitted on in the same batch of `process.nextTick()` 891operations, or whenever multiple events are emitted synchronously. Specifically, 892because the `process.nextTick()` queue is drained before the `Promise` microtask 893queue, and because `EventEmitter` emits all events synchronously, it is possible 894for `events.once()` to miss an event. 895 896```js 897const { EventEmitter, once } = require('events'); 898 899const myEE = new EventEmitter(); 900 901async function foo() { 902 await once(myEE, 'bar'); 903 console.log('bar'); 904 905 // This Promise will never resolve because the 'foo' event will 906 // have already been emitted before the Promise is created. 907 await once(myEE, 'foo'); 908 console.log('foo'); 909} 910 911process.nextTick(() => { 912 myEE.emit('bar'); 913 myEE.emit('foo'); 914}); 915 916foo().then(() => console.log('done')); 917``` 918 919To catch both events, create each of the Promises *before* awaiting either 920of them, then it becomes possible to use `Promise.all()`, `Promise.race()`, 921or `Promise.allSettled()`: 922 923```js 924const { EventEmitter, once } = require('events'); 925 926const myEE = new EventEmitter(); 927 928async function foo() { 929 await Promise.all([once(myEE, 'bar'), once(myEE, 'foo')]); 930 console.log('foo', 'bar'); 931} 932 933process.nextTick(() => { 934 myEE.emit('bar'); 935 myEE.emit('foo'); 936}); 937 938foo().then(() => console.log('done')); 939``` 940 941## `events.captureRejections` 942<!-- YAML 943added: v12.16.0 944--> 945 946> Stability: 1 - captureRejections is experimental. 947 948Value: {boolean} 949 950Change the default `captureRejections` option on all new `EventEmitter` objects. 951 952## events.captureRejectionSymbol 953<!-- YAML 954added: v12.16.0 955--> 956 957> Stability: 1 - captureRejections is experimental. 958 959Value: `Symbol.for('nodejs.rejection')` 960 961See how to write a custom [rejection handler][rejection]. 962 963## events.on(emitter, eventName) 964<!-- YAML 965added: v12.16.0 966--> 967 968* `emitter` {EventEmitter} 969* `eventName` {string|symbol} The name of the event being listened for 970* Returns: {AsyncIterator} that iterates `eventName` events emitted by the `emitter` 971 972```js 973const { on, EventEmitter } = require('events'); 974 975(async () => { 976 const ee = new EventEmitter(); 977 978 // Emit later on 979 process.nextTick(() => { 980 ee.emit('foo', 'bar'); 981 ee.emit('foo', 42); 982 }); 983 984 for await (const event of on(ee, 'foo')) { 985 // The execution of this inner block is synchronous and it 986 // processes one event at a time (even with await). Do not use 987 // if concurrent execution is required. 988 console.log(event); // prints ['bar'] [42] 989 } 990 // Unreachable here 991})(); 992``` 993 994Returns an `AsyncIterator` that iterates `eventName` events. It will throw 995if the `EventEmitter` emits `'error'`. It removes all listeners when 996exiting the loop. The `value` returned by each iteration is an array 997composed of the emitted event arguments. 998 999[WHATWG-EventTarget]: https://dom.spec.whatwg.org/#interface-eventtarget 1000[`--trace-warnings`]: cli.html#cli_trace_warnings 1001[`EventEmitter.defaultMaxListeners`]: #events_eventemitter_defaultmaxlisteners 1002[`domain`]: domain.html 1003[`emitter.listenerCount()`]: #events_emitter_listenercount_eventname 1004[`emitter.removeListener()`]: #events_emitter_removelistener_eventname_listener 1005[`emitter.setMaxListeners(n)`]: #events_emitter_setmaxlisteners_n 1006[`fs.ReadStream`]: fs.html#fs_class_fs_readstream 1007[`net.Server`]: net.html#net_class_net_server 1008[`process.on('warning')`]: process.html#process_event_warning 1009[stream]: stream.html 1010[capturerejections]: #events_capture_rejections_of_promises 1011[rejection]: #events_emitter_symbol_for_nodejs_rejection_err_eventname_args 1012[rejectionsymbol]: #events_events_capturerejectionsymbol 1013[error]: #events_error_events 1014