Async Patterns in Node.js
Callbacks, Promises, async/await, and promisify — from callback hell to clean async code
Skills taught: node.callbacks, node.promises, node.async-await, node.promisify
Evolution of async patterns
const fs = require('fs');
const util = require('util');
// ── 1. Callbacks (original Node.js style) ──
fs.readFile('./data.json', 'utf8', (err, data) => {
if (err) { console.error('Callback error:', err.message); return; }
console.log('Callback result:', JSON.parse(data).length, 'items');
// Nested callbacks — "callback hell"
fs.readFile('./notes.txt', 'utf8', (err2, notes) => {
if (err2) return console.error(err2.message);
console.log('Notes:', notes.slice(0, 30));
});
});
// ── 2. util.promisify — callbacks → Promises ──
const readFile = util.promisify(fs.readFile);
readFile('./data.json', 'utf8')
.then(data => console.log('Promise:', JSON.parse(data).length, 'items'))
.catch(err => console.error('Promise error:', err.message));
// ── 3. async/await (modern — use this) ──
async function loadFiles() {
try {
// Sequential: wait for each
const data = await readFile('./data.json', 'utf8');
const notes = await readFile('./notes.txt', 'utf8');
console.log('async/await: data items:', JSON.parse(data).length);
console.log('async/await: notes:', notes.slice(0, 30));
// Parallel: run concurrently
const [d, n] = await Promise.all([
readFile('./data.json', 'utf8'),
readFile('./notes.txt', 'utf8'),
]);
console.log('Parallel: both loaded.');
} catch (err) {
console.error('Async error:', err.message);
}
}
loadFiles();
Tip: Use Promise.all() to run independent async operations in parallel. Sequential awaits run one at a time — if each takes 100ms and you have 3 of them, sequential takes 300ms, parallel takes ~100ms.
Frequently Asked Questions
What happens if I forget `await` in an async function?
The Promise is created and starts executing, but you don't wait for it. If you use the result immediately (e.g., const data = fetchUser(id); console.log(data.name)), data is a Promise object, not the resolved value — you'll get undefined or an error. More dangerously: errors inside unresolved Promises become unhandled rejections. In Node 15+, unhandled rejections crash the process. Always await or .catch() Promises you care about.