Skip to content

Synchronous v/s Asynchronous 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: End waits until the file is fully read.
  • 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: End prints before file content, because reading is done asynchronously.
FeatureSynchronousAsynchronous
ExecutionBlocking (one at a time)Non-blocking (can do other work while waiting)
PerformanceSlower for I/O-heavy appsFaster & efficient for I/O
Use caseScripts, small tasksAPIs, servers, DB queries
Examplefs.readFileSyncfs.readFile / async/await
  • 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.
  • 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).