Learn Promises in JavaScript through Relatives Mafia in India

Imagine you are an UPSC (any competitive exam) aspirant or trying to get an off-campus job but you need to attend a marriage function and definitely relatives will be there to ask lot of questions and make you feel like a loser.
The Three States
First they will ask you what are you doing now?
You will say i am upskilling myself from chai code to get a job.
Then they will say are you sure? There is no job in IT and everybody is getting laid off and with AI there will be no job left you better leave these and join in 9 rupees Wala course ( iykyk π) to learn AI and get job in just 30 days i have seen him on YouTube you should try that.
Then you promised them that you will get job as a full stack web developer by the end of this year .
There are 2 possibilities either you get job or not and there will be some time required to know whether you get a job or not in that time they won't bother you they will do their own work.
Similarly, in JavaScript you will have 3 states : pending, resolved, rejected.
When we create a new promise the initial state is always pending.
but when it gets success the state becomes resolved.
If it is a failure then state becomes rejected.
const getJob = new Promise((resolve, reject) => {
const hasOfferletter = true; //can be false also if there is no luck or skill issue (life is unfair)
if (hasOfferletter) {
resolve("I got job as web developer.");
} else {
reject("sorry, i will take that 9rs course and build next open ai π");
}
});
we can handle or consume the promise with then and catch.
then will take the resolved callback and catch takes care of rejected callback.
getJob
.then((success) => {
console.log(success);
})
.catch((apology) => {
console.log(apology);
});
// Output : I got job as web developer.
Handling Multiple Promises
It is possible that we can do multiple promises to our relatives it can be building a home or buying a car or getting 7(saath)cr package.
In promises we can handle multiple promises with different methods:
Promise.all() : All or Nothing
You promised the relatives three things to prove your success: getting an IT job , building a house , and buying a luxury car .
This is like either succeeding all or none.
we can pass array of promises and only it gets resolved if all promises gets resolved and get an array of result, if not it will be in rejected state.
const getJob = new Promise((resolve, reject) => {
const hasOfferletter = true;
if (hasOfferletter) {
resolve("I got job as web developer.");
} else {
reject("sorry,i will take that 9rs course and build next open ai π");
}
});
const buildHome = new Promise((resolve,reject)=>{
const hasMoney = true;
if(hasMoney){
resolve("Hello uncle ji,this is invitation for my house warming ceremony.")
}
else{
reject("uncle ji, hum jeevan bhar rented house mein rahenge.")
}
})
const buyCar = new Promise((resolve,reject)=>{
const hasMoney = true;
if(hasMoney){
resolve("Uncle ji,let's go on a trip in my brandnew BMW car");
}
else{
resolve("Uncle ji,mein toh tvs xl se kaam chala lunga.")
}
})
Promise.all([getJob,buildHome,buyCar])
.then((success)=>{
console.log(success);
})
.catch((failure)=>{
console.log(failure)
})
Promise.any() : The Desperation to shut the relatives up
You are desperate to avoid embarrassment. You applied for UPSC, an off-campus IT job, and tried starting a YouTube channel. You just need one of these to work out to shut the relatives up.
promise.any() ignores all your failures (rejections) and fulfills the very second your first success comes through. It only rejects if every single plan flops which gives an AggregateError β> meaning maximum relative taunts.
const upsc = new Promise((resolve, reject) => reject("Failed prelims."));
const youtube = new Promise((resolve, reject) => reject("Only 1 subscriber(that is me only)."));
const itJob = new Promise((resolve, reject) => resolve("Got the off-campus job!"));
Promise.any([upsc, youtube, itJob])
.then((success) => {
console.log("Me at the function:", success);
})
.catch((totalFailure) => {
console.log("Time to buy that 9rs course...", totalFailure);
});
Promise.race() : The Race to make or break you
The relatives are highly impatient. They are hovering over your shoulder while you wait for your results on your phone. They don't have the patience to wait for all your results to come out.
The rule is simple: The very first notification that pops up is the final verdict. If a rejection email comes first, they instantly announce to the whole marriage hall that you are a failure, completely ignoring the massive job offer that arrives five minutes later. Conversely, if a job offer comes first, you are the star of the night, and they don't care about the exam you failed later.
Promise.race() returns the result of the fastest promise, whether it is a success (resolved) or a failure (rejected). The rest are ignored.
const tcsOffer = new Promise((resolve, reject) => {
setTimeout(() => resolve("Ji, I got the TCS job!"), 5000);
});
const upscResult = new Promise((resolve, reject) => {
setTimeout(() => resolve("Cleared UPSC Prelims!"), 10000);
});
const startupRejection = new Promise((resolve, reject) => {
setTimeout(() => reject("Beta, even the local startup rejected you?"), 2000);
});
// The Relatives are watching your phone...
Promise.race([tcsOffer, upscResult, startupRejection])
.then((fastestSuccess) => {
console.log("Relatives shouting happily:", fastestSuccess);
})
.catch((fastestFailure) => {
console.log("Relatives taunting immediately:", fastestFailure);
});
// Output: Relatives taunting immediately: Beta, even the local startup rejected you?
Promise.allSettled() : The Gossip report
The relatives are sitting in a circle eating paneer tikka, and they want the full update. They don't care if you succeeded or failed at every single thing; they just want the complete report card to gossip about.
Promise.allSettled() waits for all your promises to finish. It never rejects the whole batch. Instead, it returns an array telling the relatives exactly which plans fulfilled and which ones rejected.
const getJob = new Promise((resolve, reject) => {
const hasOfferletter = true;
if (hasOfferletter) {
resolve("I got job as web developer.");
} else {
reject("sorry,i will take that 9rs course and build next open ai π");
}
});
const buildHome = new Promise((resolve,reject)=>{
const hasMoney = true;
if(hasMoney){
resolve("Hello uncle ji,this is invitation for my house warming ceremony.")
}
else{
reject("uncle ji, hum jeevan bhar rented house mein rahenge.")
}
})
const buyCar = new Promise((resolve,reject)=>{
const hasMoney = true;
if(hasMoney){
resolve("Uncle ji,let's go on a trip my brandnew BMW car");
}
else{
resolve("Uncle ji,mein toh tvs xl se kaam chala lunga.")
}
})
Promise.allSettled([getJob, buildHome, buyCar])
.then((results) => {
console.log("Relatives gossip report:", results);
});
//Output:
// Relatives gossip report: [
// { status: 'fulfilled', value: 'I got job as web developer.' },
// {
// status: 'fulfilled',
// value: 'Hello uncle ji,this is invitation for my house warming ceremony.'
// },
// {
// status: 'fulfilled',
// value: "Uncle ji,let's go on a trip my brandnew BMW car"
// }
//]
Conclusion
Ultimately, JavaScript Promises are just like surviving a family wedding: they start as pending hopes, eventually resolving into success or rejecting into career advice.
Whether you need to satisfy all expectations (Promise.all), flex your first win (Promise.any), survive the complete gossip report (Promise.allSettled), or win the notification sprint (Promise.race), mastering these methods help you. Hope you enjoyed reading the blog π₯°.