βοΈ Day 7: Introduction to Asynchronous Programming in Node.js (Using Callbacks)

Table of contents
- π¨βπ« What Youβll Learn Today
- π§ Why Asynchronous Programming?
- π Synchronous vs Asynchronous
- π What is a Callback?
- π Real-Life Example: Reading a File (Async vs Sync)
- π§ Callback Structure
- π§ Real-World Use: Simulating a User Registration System
- π« Common Callback Mistake: Callback Hell
- β Where Are Callbacks Commonly Used?
- β FAQs β Frequently Asked Questions
- π Practice Tasks
- β Summary
- π Stay Connected
π¨βπ« What Youβll Learn Today
What is synchronous vs asynchronous programming
What are callbacks and why we use them
How Node.js handles async code
Real-life practical examples
Common mistakes and how to fix them
FAQs to clear all confusion
π§ Why Asynchronous Programming?
In Node.js, most tasks like:
reading a file
sending an email
making a database call
...take time β³
If we wait for each task to complete before starting the next one, the app will become slow and unresponsive.
Thatβs where asynchronous programming helps!
π Synchronous vs Asynchronous
π΄ Synchronous (Blocking)
console.log("1");
console.log("2");
console.log("3");
β Output:
1
2
3
Everything runs one after another, blocking the next line.
π’ Asynchronous (Non-blocking)
console.log("1");
setTimeout(() => {
console.log("2 (after delay)");
}, 1000);
console.log("3");
β Output:
1
3
2 (after delay)
π§ Here, setTimeout
is asynchronous β it lets the rest of the code run without waiting.
π What is a Callback?
A callback is a function passed as an argument to another function, to be called later when the task is done.
π Think of it like this:
"Hey Node.js, go read this file. When you're done, call this function."
π Real-Life Example: Reading a File (Async vs Sync)
π‘ Sync (blocking)
const fs = require('fs');
const data = fs.readFileSync('info.txt', 'utf-8');
console.log(data); // File content
console.log("This runs after file read");
Everything waits until file is fully read. Not good for large files or high traffic.
π’ Async with Callback (non-blocking)
const fs = require('fs');
fs.readFile('info.txt', 'utf-8', (err, data) => {
if (err) return console.error(err);
console.log(data); // File content
});
console.log("This runs immediately!");
β Output:
This runs immediately!
(File content appears later)
π§ Callback Structure
function task(callback) {
// Do something
callback(); // Call the function passed in
}
Example:
function greet(name, callback) {
console.log(`Hi, ${name}`);
callback();
}
function bye() {
console.log("Goodbye!");
}
greet("Payal", bye);
β Output:
Hi, Payal
Goodbye!
π§ Real-World Use: Simulating a User Registration System
function registerUser(name, callback) {
setTimeout(() => {
console.log(`β
User ${name} registered!`);
callback(); // call next step
}, 2000);
}
function sendWelcomeEmail() {
console.log("π§ Welcome email sent!");
}
registerUser("Payal", sendWelcomeEmail);
β Output:
β
User Payal registered!
π§ Welcome email sent!
π« Common Callback Mistake: Callback Hell
When we nest too many callbacks, it becomes hard to read:
step1(() => {
step2(() => {
step3(() => {
step4(() => {
// π© deep and messy!
});
});
});
});
π‘ This is called callback hell. Weβll solve it using Promises and Async/Await in upcoming lessons.
β Where Are Callbacks Commonly Used?
Task | Callback Example |
File system | fs.readFile() |
Database queries | db.find({}, callback) |
HTTP requests | http.get(url, callback) |
Timers | setTimeout(callback, time) |
β FAQs β Frequently Asked Questions
1) Why not always use synchronous (Sync
) versions?
Synchronous methods block your server. For example:
One user uploading a big file can freeze the server for others.
Async with callbacks keeps everything fast and smooth.
2) What is the difference between callback()
and callback
?
Syntax | Meaning |
callback | Passing the function reference |
callback() | Calling the function immediately |
3) Is setTimeout()
async or sync?
β Itβs asynchronous. It lets the program continue without waiting for the timer.
4) Can we return a value from a callback?
No, you can't return a value out of an async callback like normal functions.
Instead, you use the data inside the callback.
β Doesnβt work:
let data = fs.readFile('file.txt', 'utf-8', (err, result) => {
return result;
});
console.log(data); // undefined!
β Correct:
fs.readFile('file.txt', 'utf-8', (err, result) => {
console.log(result); // use it here
});
π Practice Tasks
Create a function
fetchData
that takes a callback and logs a message after 2 seconds.Read any file using both
readFileSync
andreadFile
β compare the order.Simulate user login, email verification, and welcome message using nested callbacks.
β Summary
Concept | Meaning / Use |
Asynchronous code | Doesnβt block the flow, runs later |
Callback | A function passed to be executed later |
fs.readFile() | Async file reading using callback |
Callback Hell | Too many nested callbacks β hard to manage |
π Congratulations! Youβve completed your first step into asynchronous programming in Node.js.
π Stay Connected
If you found this article helpful and want to receive more such beginner-friendly and industry-relevant Node JS notes, tutorials, and project ideas β π© Subscribe to our newsletter by entering your email below.
And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment, π₯ Donβt forget to subscribe to my YouTube channel β Knowledge Factory 22 β for regular content on tech concepts, career tips, and coding insights!
Stay curious. Keep building. π
Subscribe to my newsletter
Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Payal Porwal
Payal Porwal
Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: π In-depth explorations of emerging technologies π‘ Practical tutorials and how-to guides π§Insights on software development best practices πReviews of the latest tools and frameworks π‘ Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Letβs connect and grow together! π