EventEmitter vs. Callbacks
Explore the differences between EventEmitter instances and callbacks in Node.js asynchronous APIs. Learn how to choose based on event semantics and usage, and discover how combining both provides flexible asynchronous control and detailed event handling.
We'll cover the following...
A common dilemma when defining an asynchronous API is deciding whether to use an EventEmitter instance or simply accept a callback. The general differentiating rule is semantic: callbacks should be used when a result must be returned in an asynchronous way, while events should be used when there’s a need to communicate that something has happened.
But besides this simple principle, a lot of confusion is generated from the fact that the two paradigms are, most of the time, equivalent and allow us to achieve the same results. Consider the following code as an example:
The two functions helloEvents() and helloCallback() can be considered equivalent in terms of functionality. The first communicates the completion of the timeout using an event, while the second uses a callback. But what ...