Callbacks and Callback Hell
Understand callback-based async, identify the nesting problem known as callback hell, and see why Promises were introduced to solve it.
What Are Callbacks?
A callback is a function passed as an argument to another function, to be called later when some work is complete. Callbacks are the original JavaScript async pattern — they predate Promises.
// Synchronous callback:
[1, 2, 3].forEach(function(n) {
console.log(n);
});
// Async callback:
setTimeout(function() {
console.log('1 second later');
}, 1000);Node.js Error-First Callbacks
Node.js standardised a convention: callbacks receive an error as the first argument and the result as the second. If err is null/undefined, the operation succeeded.
fs.readFile('data.json', 'utf8', function(err, data) {
if (err) {
console.error('Failed to read file:', err);
return;
}
console.log('File contents:', data);
});