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

Payal PorwalPayal Porwal
4 min read

πŸ‘¨β€πŸ« 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?

TaskCallback Example
File systemfs.readFile()
Database queriesdb.find({}, callback)
HTTP requestshttp.get(url, callback)
TimerssetTimeout(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?

SyntaxMeaning
callbackPassing 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

  1. Create a function fetchData that takes a callback and logs a message after 2 seconds.

  2. Read any file using both readFileSync and readFile – compare the order.

  3. Simulate user login, email verification, and welcome message using nested callbacks.


βœ… Summary

ConceptMeaning / Use
Asynchronous codeDoesn’t block the flow, runs later
CallbackA function passed to be executed later
fs.readFile()Async file reading using callback
Callback HellToo 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. πŸš€

0
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! 🌟