Combining callbacks and events
In some cases, you can use an EventEmitter alongside a callback. This pattern is very powerful and useful when you need to handle the final result of an asynchronous operation with a callback, but also want to emit progress events as the operation is ongoing. This approach gives you the best of both worlds, allowing for granular event tracking while still providing a way to propagate a final result.
A traditional example is downloading a file from a URL. We can create a function that uses a callback to signal when the download is complete. At the same time, the function can return an EventEmitter to track the download’s progress. This allows us to display real-time updates, such as the percentage of completion, on the screen.
Before diving into the code, it’s important to note that we’ll be building an HTTPS client that follows a request/response flow. Here’s a breakdown of the main steps:
- Client request...