Synchronous vs asynchronous code in Node.js
Sync vs Async in Node.js
Node.js is single-threaded. Understanding synchronous vs asynchronous execution is fundamental to writing performant, non-blocking Node.js code.
Synchronous (Blocking)
Synchronous code blocks the event loop — nothing else runs until the operation completes.
js
const fs = require('fs');
// BLOCKING — waits until file is fully read
const data = fs.readFileSync('./file.txt', 'utf8');
console.log(data);
console.log('This runs after file is read');Problem: If reading a 1GB file, all other requests are blocked!
Asynchronous (Non-blocking)
Async code hands off the operation and continues executing. The callback/Promise runs when the operation completes.
Callbacks (old style)
js
const fs = require('fs');
fs.readFile('./file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
console.log('This runs BEFORE file is read!');Promises
js
const fs = require('fs').promises;
fs.readFile('./file.txt', 'utf8')
.then(data => console.log(data))
.catch(err => console.error(err));
console.log('This runs BEFORE file is read!');async/await (modern)
js
const fs = require('fs').promises;
async function readFile() {
try {
const data = await fs.readFile('./file.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
readFile();
console.log('This runs BEFORE file is read!');What Happens Under the Hood
Async I/O request
↓
libuv thread pool (OS handles it)
↓
Event Loop polls for completion
↓
Callback/Promise resolves on main threadThe main thread is never blocked — it keeps processing other events.
Common Async Patterns
| Pattern | Pros | Cons |
|---|---|---|
| Callbacks | Simple, universal | Callback hell, hard to read |
| Promises | Chainable, better error handling | Verbose for complex flows |
| async/await | Readable, linear flow | Needs try/catch |
Rule of Thumb
- Never use sync I/O in production server code (
readFileSync,writeFileSync, etc.) - Use async/await for most use cases
- Use
Promise.all()to run multiple async operations in parallel
js
// Parallel execution — much faster!
const [users, posts] = await Promise.all([
fetchUsers(),
fetchPosts()
]);Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.