Callbacks and Events in NodeJS
Last Updated :
19 Feb, 2025
Callbacks and events are fundamental building blocks for asynchronous programming in NodeJS. They're essential for handling operations that might take some time, ensuring your application handles asynchronous operations smoothly.
Callback in NodeJS
In NodeJS, Callbacks are functions 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.
JavaScript
function fetchData(callback) {
setTimeout(() => {
const data = 'Sample Data';
callback(null, data);
}, 1000);
}
fetchData((error, data) => {
if (error) {
console.error('Error:', error);
} else {
console.log('Data:', data);
}
});
In this example
- fetchData simulates an asynchronous operation using setTimeout.
- It accepts a callback function to handle the result.
- After 1 second, it calls the callback with null (indicating no error) and the data.
- The callback checks for errors and logs the data if successful.
Output:
Callback in NodeJSTypes of Callbacks
- Synchronous Callback: A callback that is executed immediately within the same function execution.
- Asynchronous Callback: A callback that is executed after an asynchronous operation completes.
To learn more about callbacks, you can refer to the Article - Callback in NodeJS
Events 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.
JavaScript
const EventEmitter = require('events');
// Create a new instance of EventEmitter
const eventEmitter = new EventEmitter();
// Register an event listener for the 'greet' event
eventEmitter.on('greet', () => {
console.log('Hello, welcome to Node.js!');
});
// Emit the 'greet' event
eventEmitter.emit('greet');
In this example
- We use EventEmitter to create something that can send and listen for events.
- eventEmitter.on is how we say "Hey, when the 'greet' event happens, run this code."
- eventEmitter.emit is how we actually make the 'greet' event happen. This triggers the code we set up to run.
Output:
Events in NodeJSTo learn more about events in NodeJS, check out the article - Events in NodeJS
Callbacks vs Events
Feature | Callbacks | Events |
---|
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 |
Similar Reads
What is a callback function in Node? In the context of NodeJS, a callback function is a function that is passed as an argument to another function and is executed after the completion of a specific task or operation. Callbacks are fundamental to the asynchronous nature of NodeJS, allowing for non-blocking operations and enabling effici
2 min read
Node Callback Concept A callback in Node is a non-blocking function that executes upon task completion, enabling asynchronous processing. It facilitates scalability by allowing Nodejs to handle multiple requests without waiting for operations to conclude, as exemplified in file I/O scenarios.Explanation: The fs library i
2 min read
What is Callback Hell and How to Avoid it in NodeJS? In NodeJS, asynchronous programming can lead to Callback Hell, where deeply nested callbacks make the code hard to read and maintain. This happens when multiple asynchronous operations are chained together, creating a complex structure that's difficult to manage. Callback Hell in NodeJSCallback Hell
6 min read
What is callback hell in Node.js ? To know what is callback hell, we have to start with Synchronous and Asynchronous Javascript. What is Synchronous Javascript? In Synchronous Javascript, when we run the code, the result is returned as soon as the browser can do. Only one operation can happen at a time because it is single-threaded.
3 min read
Event Demultiplexer in Node.js Node.js is designed to handle multiple tasks efficiently using asynchronous, non-blocking I/O operations. But how does it manage multiple operations without slowing down or blocking execution? The answer lies in the Event Demultiplexer.The Event Demultiplexer is a key component of Node.js's event-dr
3 min read