Synchronous v/s Asynchronous Code
๐น 1. Synchronous Code
Section titled โ๐น 1. Synchronous Codeโ- Code runs line by line, blocking until a task finishes.
- If one operation takes time(eg. reading a large files, querying DB), the whole program waits.
- Eg:
const fs = require('fs'); console.log('Start')
// Synchronous file read (blocks until file is read) const data = fs.readFileSync('file.txt', 'utf-8'); console.log(data)
console.log('End')- Output:
Start File content: <file contents> End- ๐ Notice:
Endwaits until the file is fully read.
๐น 2. Asynchronous Code
Section titled โ๐น 2. Asynchronous Codeโ- Code runs non-blocking.
- Tasks that takes time(I/O, network, DB queries) are delegated, Node.js uses the event loop to continue running other code.
- When the task finishes, a callback, promises, async/await handles the result.
- Eg:
const fs = require("fs");
console.log("Start");
// Asynchronous file read (non-blocking) fs.readFile("file.txt", "utf-8", (err, data) => { if (err) throw err; console.log("File content:", data); });
console.log("End");- Output:
Start End File content: <file contents>- ๐ Notice:
Endprints before file content, because reading is done asynchronously.
๐น 3. Comparison Table
Section titled โ๐น 3. Comparison Tableโ| Feature | Synchronous | Asynchronous |
|---|---|---|
| Execution | Blocking (one at a time) | Non-blocking (can do other work while waiting) |
| Performance | Slower for I/O-heavy apps | Faster & efficient for I/O |
| Use case | Scripts, small tasks | APIs, servers, DB queries |
| Example | fs.readFileSync | fs.readFile / async/await |
๐น 4. Real-world Analogy
Section titled โ๐น 4. Real-world Analogyโ- Synchronous = At a restaurant, you order food and wait at the counter until itโs ready. Nobody else can order until you get your food.
- Asynchronous = You order food, get a token, and sit down. The restaurant continues serving other customers. When your food is ready, they call your token.
๐น 5. Best Practice in Node.js
Section titled โ๐น 5. Best Practice in Node.jsโ- Node.js is single-threaded โ long synchronous tasks block everything.
- Always prefer asynchronous code for I/O (file, DB, HTTP).
- Use synchronous code only in quick operations (config loading, small calculations).