In this lesson, you gave washer 1 a way to tell two housemates that its cycle had ended, without the washer knowing who was listening, and saw exactly when each of them hears it.
Key Points
- A callback tells one function when something is done. Washer 1 has to tell two people, Ines and Kofi, and it shouldn’t have to know who’s listening.
- Node’s
EventEmitterclass, from thenode:eventsmodule, makes an object that announces events. You import it as you would from any module, andnew EventEmitter()makes the washer. washer.on("done", listener)adds a listener for the"done"event: a callback to run when that event happens. A second.on()call for the same event adds a second listener.- Adding a listener doesn’t run it. Nothing has happened to the washer yet.
washer.emit("done", "Ines")announces the"done"event. Whatever you pass after the event’s name goes to every listener, so each listener’snameparameter gets"Ines".emit()calls each listener itself, on the same call stack, one after the other, in the order you added them. Only when both listeners have finished doesemit()return, and the line after it runs.emit()never goes near the task queue. In the script below, the timer is what waited: the event loop moved the cycle callback onto the empty stack, and everything after that ran in that one task.- The washer doesn’t remember its events. A listener you add once the washer has already emitted is too late, and it never hears that
emit()call.
The rule: emit() calls every listener for its event right away, in the order you added them, before the next line runs.