A callback is a function passed as an argument to another function. The receiving function can call the callback when a particular task is completed or when an event occurs.
JavaScript allows us to pass functions as arguments. This makes callbacks useful for calculations, event handling, and asynchronous tasks such as reading files.
function greet(name, callback) {
console.log('Hello ' + name);
callback();
}
function message() {
console.log('Welcome to Node.js!');
}
greet('Rahul', message);
Hello Rahul
Welcome to Node.js!
Here, message is passed as a callback.
The greet() function calls it using
callback().
We can pass a function directly without giving it a separate name. Such a function is commonly called an anonymous function.
function calculate(a, b, callback) {
callback(a + b);
}
calculate(10, 20, function (result) {
console.log('Sum:', result);
});
Sum: 30
The callback receives the sum and displays it.
Arrow functions can also be used as callbacks. They often make callback code shorter and easier to read.
function calculate(a, b, callback) {
callback(a * b);
}
calculate(5, 4, (result) => {
console.log('Multiplication:', result);
});
Multiplication: 20
The arrow function receives the multiplication result and prints it.
A synchronous callback is called during the execution of the function that receives it.
function processData(callback) {
console.log('Processing data...');
callback();
}
processData(function () {
console.log('Data processed.');
});
console.log('Program finished.');
Processing data...
Data processed.
Program finished.
The callback executes before
processData() returns.
An asynchronous callback can run later, after an operation or delay. Node.js uses callbacks for many asynchronous operations.
console.log('Start');
setTimeout(function () {
console.log('Callback executed.');
}, 2000);
console.log('End');
Start
End
Callback executed.
The callback is scheduled to run after approximately two seconds. The synchronous statements run first.
We can pass values to a callback so it can use the result of another operation.
function calculateSquare(number, callback) {
const result = number * number;
callback(result);
}
calculateSquare(6, function (answer) {
console.log('Square:', answer);
});
Square: 36
The calculated result is passed to the callback as an argument.
Many Node.js APIs use the error-first callback pattern. The first argument represents an error, and the next argument or arguments contain the result.
If the operation succeeds, the error argument is usually
null. If it fails, the callback receives an error.
function divide(a, b, callback) {
if (b === 0) {
callback(new Error('Cannot divide by zero'));
return;
}
callback(null, a / b);
}
divide(10, 2, function (err, result) {
if (err) {
console.log('Error:', err.message);
return;
}
console.log('Result:', result);
});
Result: 5
The callback checks the error first. If an error exists, it handles the error and returns before using the result.
The Node.js File System module supports callback-based operations.
For example, fs.readFile() can read a file
asynchronously and pass its result to a callback.
First, create a file named message.txt:
Hello from a Node.js file!
Now create read.js:
const fs = require('fs');
fs.readFile('message.txt', 'utf8', function (err, data) {
if (err) {
console.log('Error:', err.message);
return;
}
console.log(data);
});
Hello from a Node.js file!
The callback receives an error and the file contents. If the file cannot be read, the error is handled first.
Callback hell occurs when several asynchronous operations are nested inside one another. Deep nesting can make code harder to read and maintain.
setTimeout(() => {
console.log('Step 1');
setTimeout(() => {
console.log('Step 2');
setTimeout(() => {
console.log('Step 3');
}, 1000);
}, 1000);
}, 1000);
Step 1
Step 2
Step 3
For complex asynchronous workflows, Promises and
async/await can make code easier to organize.
We will study these in upcoming lessons.
| Concept | Meaning |
|---|---|
| Callback | A function passed to another function. |
| Synchronous callback | Runs during the current function call. |
| Asynchronous callback | Runs later when the scheduled operation is ready. |
| Error-first callback | Receives an error as its first argument. |
| Callback hell | Deeply nested callbacks that are difficult to manage. |
| callback() | Calls the function stored in the callback parameter. |
setTimeout() to call a function after three seconds.fs.readFile() and handle possible errors.Challenge: Create three asynchronous steps using callbacks and display their results in order.
Select the correct answer for each question.
1. What is a callback function?
2. In a common Node.js error-first callback, what is the first argument?
3. Which function is commonly used to read a file asynchronously with a callback?