Understanding JavaScript Promises Through Pizza Delivery π

π Introduction: Why Do We Need Promises?
JavaScript is a single-threaded language β it handles one task at a time. But in modern apps, we often need to handle asynchronous operations, like:
Fetching data from a server
Reading files
Waiting for timeouts
Earlier, we used callbacks, but they often led to messy, nested code β a situation known as callback hell π©.
Thatβs where Promises come in β a cleaner way to handle async tasks in JavaScript.
π Real-Life Analogy: Ordering a Pizza
Letβs say you ordered a pizza. Youβre not just going to sit and stare at the oven β youβll probably watch Netflix or scroll through your phone.
Now the pizza can either:
Be delivered successfully β
Get canceled β
Still be in progress β³
Thatβs exactly how a Promise works β it handles a value that may be available now, later, or never.
π§βπ³ Letβs Write a Promise Function
function orderPizza() {
return new Promise((resolve, reject) => {
let pizzaReady = true;
setTimeout(() => {
if (pizzaReady) {
resolve("Yay! Pizza is here π");
} else {
reject("Oops! Pizza got canceled π");
}
}, 2000);
});
}
orderPizza()
.then((message) => {
console.log("Success:", message);
})
.catch((error) => {
console.log("Error:", error);
});
π Whatβs Happening Here?
The function
orderPizza()
returns a Promise.After a 2-second delay, it checks whether the pizza is ready.
If yes β it calls
resolve()
(promise is fulfilled).If not β it calls
reject()
(promise is rejected)..then()
handles success..catch()
handles errors.
π€ Why Use Promises?
Avoids callback hell
Makes async code easier to read and maintain
Allows chaining of multiple async steps
π Example: Promise Chaining (Bake β Deliver)
function bakePizza() {
return new Promise((resolve) => {
setTimeout(() => resolve("Pizza baked ππ₯"), 1000);
});
}
function deliverPizza() {
return new Promise((resolve) => {
setTimeout(() => resolve("Pizza delivered π΅"), 1000);
});
}
bakePizza()
.then((msg1) => {
console.log(msg1);
return deliverPizza();
})
.then((msg2) => {
console.log(msg2);
})
.catch((err) => {
console.log("Something went wrong:", err);
});
πΌοΈ Visual Recap:
Left: User places a pizza order
Middle: Pizza is being prepared (Pending)
Right: Either delivered (Fulfilled) or canceled (Rejected)
π Quick Summary
Promises represent the result of an asynchronous operation.
They can be in 3 states: Pending, Fulfilled, or Rejected.
Use
.then()
to handle success, and.catch()
for errors.Real-world analogy: Pizza ordering makes it fun to learn π
If you enjoyed this blog, give it a like β€οΈ, leave a comment π, and follow for more real-life JavaScript explanations!
Subscribe to my newsletter
Read articles from Abhishek Tiwari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
