Promises in JavaScript: Waiting for Semester Results

Mere keyboard ka F5 key ab dheere dheere apni spring lose kar raha hai.
PG room mein baitha hoon, laptop ke saamne.
University portal khula hai.
BCA final semester.
Results “sometime today” aane wale hain.
Yeh “sometime today” waala jumla…
sabse zyada pareshan karta hai.
Jab mujhe JavaScript properly samajh nahi aata thi, main code bhi bilkul waise hi likhta tha jaise abhi feel kar raha hoon: completely stuck. Tab main callbacks use karta tha. Emotionally bhi callbacks exhausting hote hain. Bilkul aisa jaise aapne university ko apna phone number de diya ho, aur phir phone ke paas freeze ho kar baith jao jab tak unka call na aaye. Control kisi aur ke haath mein chala jata hai. Sab messy lagta hai. Sab out of control.
Phir maine Promises seekhe.
Promise delay ko magically khatam nahi karta. Bas aapka us delay ke saath relationship change kar deta hai. Ye aapko ek ticket deta hai. Guarantee deta hai ki answer aayega. Aap apni reaction plan kar sakte ho aur apni life continue kar sakte ho jab tak background processes apna kaam karte rahein.
Chalo dekhte hain ye waiting ka game kaise chalta hai.
The Pending Placeholder: Promise States
JavaScript mein Promise bas ek object hota hai jo track karta hai ki koi background task finish hua ya fail. Iska matlab ye nahi hota ki “mere paas data aa gaya.” Iska matlab hota hai, “Maine tumhari request receive kar li hai, aur baad mein bataunga kya hua.”
Yeh hai mera busy university server ka imagination in actual code:
const semesterResult = new Promise((resolve, reject) => {
console.log("Checking university database...");
setTimeout(() => {
const passed = Math.random() > 0.5; // 50/50 chance of passing
if (passed) {
resolve("Congrats! You cleared the semester.");
} else {
reject("Backlog in Computer Networks.");
}
}, 2000); // 2-second server delay
});
Jab ye code run hota hai, tab ye Pending state mein baitha hota hai. Mere paas abhi grades nahi hain. Bas mera roll number hai jo line mein jagah pakad ke baitha hai. Do second baad ye settle hota hai -> ya to Fulfilled (pass) ya Rejected (fail).
Real-life coding value: Hum is setup ka use karte hain purane messy code ko clean, modern Promises mein convert karne ke liye -> jaise file read karna ya kisi data source se data lena.
Handling Results with .then(), .catch(), .finally()
Kyuki Promise future ka ticket hai, aap result aane se pehle hi instructions attach kar sakte ho. Control aapke haath mein rehta hai.
semesterResult
.then((marks) => {
console.log("Good news:", marks);
console.log("Action: Calling my parents now.");
})
.catch((error) => {
console.error("Bad news:", error);
console.log("Action: Supplementary exam form bharna padega.");
})
.finally(() => {
console.log("Pass ho ya fail, din khatam hota hi hai. Cleanup code always runs.");
});
Agar pass hua to .then() chalega -> celebration mode on.
Agar fail hua to .catch() damage control karega. Error ko catch karega taaki app crash na ho.
Sabse best part hai .finally(). Bhai result kaise bhi aaye, sunset to hona hi hai. Cleanup code har haal mein run karega.
Real-life coding value: Ye pattern online forms submit karne, user data fetch karne aur loading spinner hide karne ke liye standard hai.
Honestly, Hashnode pe blog likhte waqt mujhe same logic async/await syntax mein likhna zyada pasand hai. Ye Promises ka cleaner version hai. Bilkul ek normal story ki tarah upar se neeche flow karta hai.
const semesterResult = new Promise((resolve, reject) => {
console.log("Checking university database...");
setTimeout(() => {
const passed = Math.random() > 0.5; // 50/50 chance of passing
if (passed) {
resolve("Congrats! You cleared the semester.");
} else {
reject("Backlog in Computer Networks.");
}
}, 2000); // 2-second server delay
});
async function checkPortal() {
try {
const marks = await semesterResult;
console.log("Good news:", marks);
} catch (error) {
console.error("Bad news:", error);
} finally {
console.log("Action: Laptop band.");
}
}
checkPortal();
Behind the scenes, JavaScript is waiting beautifully. Jab network response aata hai, wo quietly queue mein add ho jata hai. Current code finish hone ka patiently wait karta hai, phir smoothly final result handover karta hai.
Instant Grades: Promise.resolve() and Promise.reject()
Kabhi kabhi delay hota hi nahi (fast effect) .
Jaise internal assignments. Professor ne marks weeks pehle upload kar diye. Internet se fetch karne ki zarurat hi nahi. Par app ko Promise chahiye smooth flow ke liye.
const internalMarks = Promise.resolve(85);
internalMarks.then(score => {
console.log(`Internal score finalized: ${score}`);
});
Ye instantly known value ko Promise ke andar wrap kar deta hai. Koi fake delay nahi.
Ab opposite case. 75% se kam attendance? Direct reject.
const attendanceStatus = Promise.reject("Shortage of attendance. Not eligible.");
attendanceStatus.catch(reason => {
console.error(reason);
});
Immediate failure. Catch block turant run.
Real-life coding value:
Promise.resolve() saved data dikhane ke liye perfect hai.
Promise.reject() early validation ke liye -> jaise empty form ko server bhejne se pehle hi rok dena.
The Strict Contract: Promise.all()
Degree ke liye ek subject pass karna enough nahi. Is semester mein 5 subjects hain.
const sub1 = new Promise(res => setTimeout(() => res("Pass: Math"), 1000));
const sub2 = new Promise((res, rej) => setTimeout(() => rej("Fail: Physics"), 1500));
const sub3 = new Promise(res => setTimeout(() => res("Pass: English"), 500));
const sub4 = new Promise(res => setTimeout(() => res("Pass: DBMS"), 1200));
const sub5 = new Promise(res => setTimeout(() => res("Pass: Operating Systems"), 800));
Promise.all([sub1, sub2, sub3, sub4, sub5])
.then(allResults => {
console.log("Graduated! Grades:", allResults);
})
.catch(firstFailure => {
console.error("Cannot graduate yet. Reason:", firstFailure);
});
.all() mein ek bhi failure aaya to pura process fail. sub2 fail hua, to seedha catch block.
Real-life coding value: Jab webpage ko multiple cheezein ek saath load karni hoti hain -> profile, stats, alerts tab useful hota hai.
The Full Picture: Promise.allSettled()
Kabhi kabhi bas full report chahiye. Crash nahi.
const sub1 = new Promise(res => setTimeout(() => res("Pass: Math"), 1000));
const sub2 = new Promise((res, rej) => setTimeout(() => rej("Fail: Physics"), 1500));
const sub3 = new Promise(res => setTimeout(() => res("Pass: English"), 500));
const sub4 = new Promise(res => setTimeout(() => res("Pass: DBMS"), 1200));
const sub5 = new Promise(res => setTimeout(() => res("Pass: Operating Systems"), 800));
Promise.allSettled([sub1, sub2, sub3, sub4, sub5])
.then(results => {
console.log("Class Status Map:");
results.forEach(result =>
console.log(result.status, result.value || result.reason)
);
});
// Class Status Map:
// fulfilled Pass: Math
// rejected Fail: Physics
// fulfilled Pass: English
// fulfilled Pass: DBMS
// fulfilled Pass: Operating Systems
Ye sabka status deta hai -> pass ya fail. Kisi ek ke fail hone se process rukta nahi.
Real-life coding value: 10 images upload kar rahe ho, 1 fail ho gayi, baaki 9 to upload hone do.
Desperation and Strategy: Promise.race()
Do ( 2 ) servers. Jo server sabse pehle respond karega, wahi fate (final result jisse hum agla step decide karte hain) decide karega. Baaki server responses background mein complete hote rehte hain, par unka result ignore kar diya jaata hai.
Jo bhi pehle hua, final answer whi hai. Fail ho ya pass, jaldi batado.
const server1 = new Promise(res => setTimeout(() => res("Server 1: Cleared!"), 300));
const server2 = new Promise((res, rej) => setTimeout(() => rej("Server 2: Failed"), 100));
Promise.race([server1, server2])
.then(result => console.log("Result that matters (fate):", result))
.catch(error => console.error("Result that matters (fate):", error));
// Result that matters (fate): Server 2: Failed
Yahan, Server2 sabse fast tha aur 100ms mein fail ho gaya. Race khatam. Humara fate yahi decide hua -> Server2 ka response final outcome ban gaya, chahe Server1 baad mein clear status de bhi.
Real-life coding value: Jab network request ke liye timeout set karna ho ya fastest response lena ho. Jaise agar 5 second mein data na aaye to error show karo.
Holding Out for a Yes: Promise.any()
Ek haan ki talaash mein…
Job applications daal diye.
Rejections ki counting nahi.
Bas ek Yes chahiye.
const jobApp1 = new Promise((res, rej) => setTimeout(() => rej("Rejected: Startup A"), 200));
const jobApp2 = new Promise((res, rej) => setTimeout(() => rej("Rejected: Agency B"), 400));
const jobApp3 = new Promise(res => setTimeout(() => res("Hired: ChaiCodeHQ"), 600));
Promise.any([jobApp1, jobApp2, jobApp3])
.then(offer => {
console.log("Result:", offer);
})
.catch(aggregateErr => {
console.error("All rejected:", aggregateErr.errors);
});
.any() fast rejections ignore karta hai. Bas first success pe resolve karta hai. Agar sab reject ho gaye, to AggregateError throw hota hai -> sab failures ek list mein.
Jab tak koi na koi succeed na ho jaye, main haar nahi manunga.
Real-life coding value: Multiple backup servers se video download try karna. Jo pehle connect kare, usko use karo.
Why Promises Make Waiting Easier
Screen ko stare karte hue mujhe ek cheez samajh aati hai.
Coding sirf logic nahi - zyada waqt unknown ko gracefully handle karne ki baat hoti hai.
Hum apps banate hain jo door ke databases aur slow internet pe depend karte hain. Hum constantly un cheezon ka wait karte hain jo humare control mein nahi hai.
Promises hume ek clean tareeka dete hain wait ko handle karne ka.
Network request fail na ho, ye guarantee nahi kar sakte. Jaise exam result ka guarantee nahi hota. Par hum aisa code likh sakte hain jo delay survive kare aur result safely handle kare.
Portal ka loading icon finally ruk gaya.
Screen ek second ke liye blank hui.
State ab pending nahi hai.
Final result aa chuka hai.
Main ek deep breath leta hoon.
Main .then() ke liye ready hoon.
Main .catch() ke liye prepared hoon.
Aur andar hi andar mujhe pata hai…
Jo bhi ho screen pe…
.finally()… main theek rahunga.




