JavaScript Promises Are Like Ordering Biryani
·
Kamesh Sethupathi
JavaScript Promises are a lot like ordering biryani from Zomato.
You place your order, and Zomato gives you a promise: "Your biryani will arrive in 30 minutes." At that point, one of three things can happen:
- The biryani arrives on time.
- The delivery guy calls and says it is out of stock.
- You're still waiting, because the biryani is still cooking.
That is how Promises work. Your app doesn't freeze while it waits. It keeps doing other things and checks on the order when it's ready.
.then()runs when the biryani arrives..catch()runs when the order fails..finally()runs either way, so you can get back to your work.
Here is a small example.
const orderBiryani = new Promise((resolve, reject) => {
const inStock = Math.random() > 0.2; // sometimes the restaurant runs out
setTimeout(() => {
if (inStock) {
resolve("Biryani arrived");
} else {
reject(new Error("Out of stock"));
}
}, 1000);
});
orderBiryani
.then((message) => console.log(message))
.catch((error) => console.log(error.message))
.finally(() => console.log("Back to my work"));
So the next time you're waiting for that biryani, or for an API call, remember that Promises always deliver... well, most of the time.
Reach me
Happy to talk about frontend and backend technologies, or about building something together.