Radhe Radhe Guy's
JavaScript Promises can sometimes feel like that one friend who says, "Bhai, kaam ho jayega!" but leaves you waiting forever. This post will break down promises in a fun and easy way with relatable Indian examples.
1. What is a Promise in JavaScript?
A Promise in JavaScript is like ordering biryani online. It will either:
Resolve β Biryani arrives and you're happy π.
Reject β Delivery guy cancels, and you're left starving π.
Example:
const biryaniOrder = new Promise((resolve, reject) => {
let biryaniReady = true;
if (biryaniReady) {
resolve('Biryani is here!');
} else {
reject('No biryani for you today.');
}
});
2. Consuming a Promise (Then and Catch)
To handle a Promise, we use .then() and .catch().
Example:
biryaniOrder
.then((message) => {
console.log(message); // Biryani is here!
})
.catch((error) => {
console.log(error); // No biryani for you today.
});
Relatable? Imagine this:
"When Zomato says 'Arriving in 10 mins' but it's been 30 mins..."
3. Promise Chaining (One Thing After Another)
Promise chaining allows sequential execution. Like ordering dessert after biryani.
Example:
biryaniOrder
.then((message) => {
console.log(message);
return 'Letβs order gulab jamun!';
})
.then((dessert) => {
console.log(dessert); // Let's order gulab jamun!
})
.catch((error) => {
console.log(error);
});
when the Gulab jamun is comingπ
4. Async/Await (The VIP Treatment)
Async/await simplifies working with promises, like being a VVIP at a wedding.
Example:
async function enjoyMeal() {
try {
let food = await biryaniOrder;
console.log(food);
console.log('Gulab jamun coming next...');
} catch (error) {
console.log(error);
}
}
enjoyMeal();
5. Why Use Promises?
- Better readability (No callback hell π)
- Easier error handling
- Clean asynchronous operations
When your relatives promise shaadi ki laddoo but ghost you later.
Thanks for reading! π€βοΈ
Top comments (1)
like and commet for such Post