Core Concepts
Async Programming
Master callbacks, Promises, and async/await for handling asynchronous operations in Node.js.
Asynchronous Node.js
Almost everything in Node.js is asynchronous. Reading files, querying databases, making HTTP requests — they all happen asynchronously.
Evolution of Async Patterns
- Callbacks (original): Functions called when operation completes. Can lead to "callback hell"
- Promises (ES6): Chainable, more readable
- async/await (ES2017): Looks synchronous, is asynchronous — the modern standard
Error Handling
- Callbacks: First argument is always an error (err-first pattern)
- Promises: Use
.catch() - async/await: Use try/catch
Example
nodejs
const fs = require('fs').promises;
// ---- Callbacks (old style) ----
const fsOld = require('fs');
fsOld.readFile('./data.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error:', err);
return;
}
console.log(data);
});
// ---- Promises ----
fs.readFile('./data.txt', 'utf8')
.then(data => console.log(data))
.catch(err => console.error(err));
// ---- async/await (recommended) ----
async function readData() {
try {
const data = await fs.readFile('./data.txt', 'utf8');
console.log(data);
} catch (err) {
console.error('Failed to read file:', err.message);
}
}
// Parallel async operations
async function fetchMultiple() {
const [users, products] = await Promise.all([
fetch('/api/users').then(r => r.json()),
fetch('/api/products').then(r => r.json()),
]);
return { users, products };
}
readData();Try it yourself — NODEJS