πŸš€ Day 8: Promises and Async/Await in Node.js

Payal PorwalPayal Porwal
7 min read

πŸ‘¨β€πŸ« What You’ll Learn Today

  • What are Promises in Node.js?

  • Why Promises are better than Callbacks

  • What is async/await and why it’s popular

  • Real-life examples for both

  • Common mistakes to avoid

  • Important FAQs


πŸ’‘ Why Use Promises?

In Day 7, we saw how callbacks can be used to handle asynchronous tasks.
But too many nested callbacks β†’ "Callback Hell" πŸ‘Ή

βœ… Promises give us clean, readable and chainable code for handling async tasks.


🧠 What is a Promise?

A Promise is an object that represents the result of an async operation.

It can have three states:

StateMeaning
PendingThe task is still running
ResolvedThe task finished successfully
RejectedThe task failed (error occurred)

πŸ“¦ Real-Life Example Using Promise

Let’s create a promise that simulates user login:

function loginUser(username, password) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (username === "admin" && password === "1234") {
        resolve("βœ… Login successful!");
      } else {
        reject("❌ Invalid credentials");
      }
    }, 2000);
  });
}

// Call the function
loginUser("admin", "1234")
  .then((msg) => console.log(msg))       // when resolved
  .catch((err) => console.log(err));     // when rejected

βœ… Output:

βœ… Login successful!

Try wrong password β†’ it will go to .catch()!


πŸ” Chaining Promises

function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("πŸ“¦ Data fetched!");
    }, 1000);
  });
}

function processData(data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(`${data} β†’ πŸ”§ Processed`);
    }, 1000);
  });
}

// Chain them
fetchData()
  .then(processData)
  .then((finalData) => console.log(finalData));

βœ… Output:

πŸ“¦ Data fetched! β†’ πŸ”§ Processed

πŸ§˜β€β™€οΈ What is async/await?

async/await is a cleaner way to work with Promises.

It looks like synchronous code, but works asynchronously behind the scenes.


πŸ”„ Convert Promise Code to Async/Await

async function doLogin() {
  try {
    const result = await loginUser("admin", "1234");
    console.log(result);
  } catch (error) {
    console.log(error);
  }
}

doLogin();

βœ… Same output:

βœ… Login successful!

🧠 await can only be used inside an async function.


βœ… Real-Life Example: File Read with Promises

Instead of fs.readFile(), use fs.promises (modern practice):

const fs = require('fs').promises;

async function readFileAsync() {
  try {
    const data = await fs.readFile('info.txt', 'utf-8');
    console.log("πŸ“„ File content:", data);
  } catch (err) {
    console.error("❌ Error reading file:", err);
  }
}

readFileAsync();

πŸ” Another Real-Life Case: User Registration Flow

function registerUser(name) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(`πŸ‘€ User ${name} registered`);
      resolve(name);
    }, 1000);
  });
}

function sendEmail(name) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(`πŸ“§ Email sent to ${name}`);
      resolve();
    }, 1000);
  });
}

async function handleRegistration() {
  const name = await registerUser("Payal");
  await sendEmail(name);
  console.log("βœ… Registration complete");
}

handleRegistration();

βœ… Output:

πŸ‘€ User Payal registered
πŸ“§ Email sent to Payal
βœ… Registration complete

❓ FAQs – Frequently Asked Questions


1) What is the difference between Callback and Promise?

FeatureCallbackPromise
Code styleNested and messyCleaner, chainable
Error catchInside callback.catch() or try/catch
ReadabilityLowHigh

2) Can we use await without async?

❌ No.
await only works inside an async function.


3) What happens if a Promise is rejected and we don’t use .catch()?

Node.js will show a warning:

UnhandledPromiseRejectionWarning

βœ… Always use .catch() or try...catch.


4) Should I use then/catch or async/await?

Both are fine, but:

Use CaseRecommended Style
Simple chain.then().catch()
Complex flowasync/await
New projectsasync/await βœ…

5) What is fs.promises and why use it?

Node.js provides fs.promises to use Promise-based file operations (like readFile, writeFile, etc.).
No need to convert manually β€” just use it directly.


πŸ“ Practice Tasks

  1. Create a fake user login using Promises and .then/.catch

  2. Convert the same into async/await version

  3. Use fs.promises to read any .txt file asynchronously

  4. Simulate order placement and payment process using chained Promises


βœ… Summary

ConceptMeaning / Use
PromiseHandle async work in a clean way
.then()Runs after success
.catch()Catches errors
async/awaitModern and readable way to write async code
fs.promisesFile system API with Promises

🌟 Mini Project: Order Processing System Using Promises + Async/Await


🎯 Project Goal

Simulate a food delivery platform where:

  1. User places an order

  2. Payment is processed

  3. Order is prepared

  4. Order is delivered

All actions are asynchronous, and we’ll handle them using Promises and async/await.


πŸ“¦ Technologies Used

  • Node.js (no third-party package required)

  • Built-in setTimeout() to simulate async delays


🧠 Concepts Covered

  • Creating and chaining Promises

  • Handling async flow using async/await

  • Error handling using try...catch


πŸ“ Step-by-Step Guide

βœ… Step 1: Create a folder

mkdir order-system
cd order-system

πŸ“„ Step 2: Create a file order.js

// order.js

function placeOrder(food) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (food) {
        console.log(`πŸ“¦ Order placed for: ${food}`);
        resolve(food);
      } else {
        reject("❌ No food item specified");
      }
    }, 1000);
  });
}

function processPayment(food) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(`πŸ’³ Payment processed for ${food}`);
      resolve(food);
    }, 1000);
  });
}

function prepareOrder(food) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(`🍳 ${food} is being prepared`);
      resolve(food);
    }, 1500);
  });
}

function deliverOrder(food) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(`🚚 ${food} delivered successfully`);
      resolve();
    }, 1000);
  });
}

πŸ”„ Step 3: Create the main async function

// Add this below the above functions in the same file

async function startOrder() {
  try {
    const food = await placeOrder("Paneer Butter Masala");
    await processPayment(food);
    await prepareOrder(food);
    await deliverOrder(food);
    console.log("βœ… Order completed!");
  } catch (error) {
    console.error("❗ Error:", error);
  }
}

startOrder();

β–Ά Step 4: Run the project

node order.js

βœ… Output:

πŸ“¦ Order placed for: Paneer Butter Masala
πŸ’³ Payment processed for Paneer Butter Masala
🍳 Paneer Butter Masala is being prepared
🚚 Paneer Butter Masala delivered successfully
βœ… Order completed!

πŸ’₯ Bonus: Try Adding a Failure Case

Replace:

await placeOrder("Paneer Butter Masala");

With:

await placeOrder(""); // no item passed

Output:

❗ Error: ❌ No food item specified

βœ… This shows how try...catch can catch promise rejections!


πŸ“š What Students Will Learn

StepConcept Learned
placeOrder()Create a Promise
awaitWait for each step to finish
setTimeout()Simulate delay (like API or DB call)
try...catchHandle errors in async/await
Flow controlUnderstanding real-world sequencing

πŸ“ Practice Suggestions for Students

  1. Add a new step: packOrder()

  2. Add user input using readline module

  3. Log timestamps to show async nature

  4. Try to run steps without await and observe the behavior


βœ… Summary

You've just built a real-world simulation of an order processing system using:

  • Promises to define async steps

  • Async/Await to write clean, readable code


πŸ”” 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! 🌟