In this brief overview, we'll cover what a callback function is and how Node.js uses it to handle asynchronous operations. We’ll start with a straightforward definition and then explore its practical applications through examples.
Callback functions are functions that you pass as an argument to another function to be executed after some operation is completed. In the context of Node.js, they are particularly useful for managing non-blocking I/O operations, ensuring your application remains responsive without waiting for these operations to complete.
To understand this better, let's first define a basic callback and see how it works in practice.
// Example of a simple callback function
function asyncOperation(callback) {
setTimeout(() => {
console.log('Async operation completed');
// Call the callback when done
callback();
}, 2000);
}
asyncOperation(() => {
console.log('Callback executed after 2 seconds');
});
Top comments (0)