EventEmitter — listeners, once, and the error event that crashes¶
Level: 201 · for readers who have attached a listener with on
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: emit runs every listener synchronously, in the order added, before it returns; and an 'error' event with no listener is not ignored like other events: emit throws it, and if nothing catches it the process exits with status 1.
Keywords: EventEmitter, emit, once, error event, setMaxListeners
What the finished page will answer¶
- In what order do a
console.logbeforeemit, two listeners and aconsole.logafteremitrun, and what doesemitreturn with and without listeners? - What happens when
emit("error", err)has no listener, and what when the error is a string rather than anError? - What does a
oncelistener do after its first call, and what doesawait events.once(emitter, "ready")return? - What warning does Node print when an 11th listener is added for one event, and what is it guessing about?
- How does
EventEmitterdiffer from theEventTargetNode also has, and which one do streams use?
Examples it will need¶
-
events_emit_is_synchronous_js.js— the log order aroundemit, andemit's return value with and without listeners -
events_error_without_listener_sh.sh— stderr and the exit status whenerroris emitted with no listener, then with one, then with a string -
events_max_listeners_warning_sh.sh— the MaxListenersExceededWarning after an 11th listener, and aoncelistener's count before and after it fires
See also¶
- DOM events — the DOM's events, which travel through a tree
- Unhandled errors — what the thrown
errorevent does next - Callbacks — listeners are callbacks, called synchronously here
- Memory leaks — the listener nobody removes
- Concurrency: How does one event reach every subscriber? ↗ — one event reaching every subscriber, in other languages
- Concurrency: Event-driven programming ↗ — event-driven programming as a model