Node.js was built around callbacks: functions passed as arguments that run when an async operation completes. Callbacks lead to deeply nested "callback hell." Promises solve this by representing a future value and supporting chaining with .then() and .catch().
Node.js
Beginner
10 min read
Callbacks and Promises
Example
const fs = require('fs');
// --- Callback style (old way) ---
fs.readFile('data.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error:', err);
return;
}
fs.writeFile('output.txt', data.toUpperCase(), (err) => {
if (err) console.error(err);
else console.log('Done writing');
});
});
// --- Promise style ---
function readFileProm(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
}
readFileProm('data.txt')
.then(data => data.toUpperCase())
.then(upper => console.log(upper))
.catch(err => console.error('Promise rejected:', err));
// --- Promise.all — run multiple promises in parallel ---
const p1 = readFileProm('file1.txt');
const p2 = readFileProm('file2.txt');
Promise.all([p1, p2])
.then(([content1, content2]) => {
console.log('Both files loaded');
})
.catch(err => console.error('One failed:', err));