![]() |
VOOZH | about |
Callbacks and events are fundamental building blocks for asynchronous programming in NodeJS. They're important for handling operations that might take some time, ensuring your application handles asynchronous operations smoothly. They are functions that are passed as arguments to other functions and executed when the task completes. This is how NodeJS handles tasks that take time, like getting data from the internet, without making your program wait.
When an asynchronous function is executed, Node.js does not wait for it to complete. Instead, it moves on to the next task and invokes the callback function once the asynchronous operation finishes.
Code Overview:
Output:
To learn more about callbacks, you can refer to the Article - Callback in NodeJS
In NodeJS, events are actions or occurrences that the application can detect and respond to, such as 'data' or 'error'. The EventEmitter class enables objects to emit events and allows listeners to handle them asynchronously, handling non-blocking operations.
Code Overview:
Output:
To learn more about events in NodeJS, check out the article - Events in NodeJS
| Feature | Callbacks | Events |
|---|---|---|
Defintion | Function is passed as an argument in another function | A Signaling mechanism where an emitter triggers events and listeners respond. |
| Execution Flow | Executes once per operation | Can be triggered multiple times |
| Code Structure | Nested and can lead to callback hell | More organized and manageable |
| Use Case | Used for single asynchronous operations | Used for handling multiple occurrences of an event |