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

Table of contents
- π¨βπ« What Youβll Learn Today
- π‘ Why Use Promises?
- π§ What is a Promise?
- π¦ Real-Life Example Using Promise
- π Chaining Promises
- π§ββοΈ What is async/await?
- β Real-Life Example: File Read with Promises
- π Another Real-Life Case: User Registration Flow
- β FAQs β Frequently Asked Questions
- π Practice Tasks
- β Summary
- π Mini Project: Order Processing System Using Promises + Async/Await
- π― Project Goal
- π¦ Technologies Used
- π§ Concepts Covered
- π Step-by-Step Guide
- π₯ Bonus: Try Adding a Failure Case
- π What Students Will Learn
- π Practice Suggestions for Students
- β Summary
- π Stay Connected
π¨βπ« 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:
State | Meaning |
Pending | The task is still running |
Resolved | The task finished successfully |
Rejected | The 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?
Feature | Callback | Promise |
Code style | Nested and messy | Cleaner, chainable |
Error catch | Inside callback | .catch() or try/catch |
Readability | Low | High |
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 Case | Recommended Style |
Simple chain | .then().catch() |
Complex flow | async/await |
New projects | async/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
Create a fake user login using Promises and
.then/.catch
Convert the same into async/await version
Use
fs.promises
to read any.txt
file asynchronouslySimulate order placement and payment process using chained Promises
β Summary
Concept | Meaning / Use |
Promise | Handle async work in a clean way |
.then() | Runs after success |
.catch() | Catches errors |
async/await | Modern and readable way to write async code |
fs.promises | File system API with Promises |
π Mini Project: Order Processing System Using Promises + Async/Await
π― Project Goal
Simulate a food delivery platform where:
User places an order
Payment is processed
Order is prepared
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
Step | Concept Learned |
placeOrder() | Create a Promise |
await | Wait for each step to finish |
setTimeout() | Simulate delay (like API or DB call) |
try...catch | Handle errors in async/await |
Flow control | Understanding real-world sequencing |
π Practice Suggestions for Students
Add a new step:
packOrder()
Add user input using
readline
moduleLog timestamps to show async nature
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. π
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! π