Node.js — Callbacks
What is a Callback?
A function passed as an argument to be executed later.
function greet(name, callback) {
console.log('Hello, ' + name);
callback();
}
greet('John', () => {
console.log('Callback executed!');
});
Error-First Callbacks
function readData(callback) {
fs.readFile('data.json', (err, data) => {
if (err) return callback(err);
callback(null, JSON.parse(data));
});
}
readData((err, data) => {
if (err) console.error(err);
else console.log(data);
});
Callback Hell
getData((a) => {
processA(a, (b) => {
processB(b, (c) => {
processC(c, (d) => {
console.log(d);
});
});
});
});
Convert to Promise
function readData() {
return new Promise((resolve, reject) => {
fs.readFile('data.json', (err, data) => {
if (err) reject(err);
else resolve(JSON.parse(data));
});
});
}
Mini Practice
- Write a callback function
- Use error-first callbacks
- Flatten callback hell
- Convert callbacks to promises
Up Next
Continue with Promises — promise-based patterns.
Related Topics
Frequently Asked Questions about Callbacks
What is Callbacks in Node.js?
Callbacks is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Callbacks?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Callbacks.
Why is Callbacks important in Node.js?
Callbacks is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.