
What is a Promise?
A Promise in Javascript is exactly what it sounds like in real life - a commitment about something that will happen in future.
We can say that when India says, "Hum ceasefire krenge, if conditions are met." That's a promise. This promise might get fulfilled, or might get rejected, but until an answer comes, that promise is still pending.
Javascript Promises work the same way. Every Promise exists in one of the three states:
| State | Meaning |
|---|---|
| Pending | Still waiting, no decision yet |
| Fulfilled | Succeeded - result is available |
| Rejected | Failed - an error occured |
Now lets see the static methods on the Promise object, these static methods are power tools which we use when we need to handle multiple promises at once, or create promises in special ways. There are in all 8 static methods.
Promise.all() - All or Nothing
Promise.all() takes an array of promises. If every single promise is fulfills, it returns an array of all their results in the same order. But if even one promise gets reject, then the entire thing rejects immediately with the rejected reason.
Global Tension with help of promise.()
The USA, UK, France, Germany, Canada, Italy, India and Japan all have agreed that they will impose sanctions on Iran only if every single nation agrees. But even if one country rejects like if Germany says that we refuse this sanction then the entire deal is called off.
Yahi philosophy hai Promise.all() ki - ek bhi fail to poora fail.
// nations voting on Iran sanctions
const usaAgrees = Promise.resolve("USA: Ready for sanctions");
const ukAgrees = Promise.resolve("UK: Ready for sanctions");
const remaingCountriesAgrees = Promise.resolve("Sabne agree krdiya hai!")
const germanyRefuses = Promise.reject("Germany: We do not agree to sanctions");
const Alliance = Promise.all([usaAgrees, ukAgrees, germanyRefuses, remainingCountriesAgree]);
Alliance
.then((results) => {
console.log("All nations agreed:", results);
// This line will NEVER run because Germany refused
})
.catch((error) => {
console.log("Alliance broke down:", error);
// Output: "Alliance broke down: Germany: We do not agree to sanctions"
});
When everyone agrees the sanction then:
const usaAgrees = Promise.resolve("USA: Ready");
const ukAgrees = Promise.resolve("UK: Ready");
const franceAgrees = Promise.resolve("France: Ready");
const remaingCountriesAgrees = Promise.resolve("Sabne agree krdiya hai!")
Promise.all([usaAgrees, ukAgrees, franceAgrees, remaingCountriesAgrees])
.then((results) => {
console.log("All nations on board:", results);
// Output: ["USA: Ready", "UK: Ready", "France: Ready", "Sabne agree krdiya hai!"]
});
Important thing to learn in promise.all()
If all fulfill - .then() gets an array of results in the same order as input
If even one rejects - .catch() fires with the first rejection reason
The other promises don't get cancelled - their results are just ignored
Use this when every operation is critical and one failure should stop everything
Promise.allSettled() - Give me Every Result, No Matter what
Promise.allSettled() also takes array of promises. But unlike Promise.all() , it waits for every single promise to either fulfill or reject. It never rejects itself. Each result is returned back as object. { status: "fulfilled"/"rejected", value/reason: ... }
Global Tension with help of promise.allSettled()
The United Nations decided to compile a full report on every country's crises, The countries are Israel, Palestine, Iran, Afghanistan, and Pakistan, Regardless they have cooperated before or not.
The UN needs a complete picture. Koi bhi country miss nahi honi chahiye, not even the ones that refuse to engage.
//UN generating report of crises aid status across conflict zones
const israelResponse = Promise.resolve("Israel: Aid corridor opened");
const iranResponse = Promise.reject("Iran: Aid blocked due to sanctions");
const afghanistanResponse = Promise.resolve("Afghanistan: Aid received successfully");
const pakistanResponse = Promise.reject("Pakistan: Unstable situation, aid delayed");
Promise.allSettled([
israelResponse,
iranResponse,
afghanistanResponse,
pakistanResponse
]).then((results) => {
results.forEach((result) => {
if (result.status === "fulfilled") {
console.log("✅ Success:", result.value);
} else {
console.log("❌ Failed:", result.reason);
}
});
});
/*
Output:
✅ Success: Israel: Aid corridor opened
❌ Failed: Iran: Aid blocked due to sanctions
✅ Success: Afghanistan: Aid received successfully
❌ Failed: Pakistan: Unstable situation, aid delayed
*/
Important thing to learn in promise.allSettled()
This never rejects - .then() always runs
Every result object has a status field: "fulfilled" or "rejected"
Fulfilled results have a value field; rejected results have a reason field
Use this when you need a full report - failures included
Promise.any() - First One to Succeed Wins
Promise.any() takes an array of promises. As soon as any one promise fulfills, it resolves with that value. It ignores all rejections along the way. Only if every single promise is rejected then it throws an Error.
Global Tension with help of promise.any()
India urgently needs oil. They contact three sources simultaneously which are Russia, Saudi Arabia and UAE's internal reserves. They just need any one of them to come through. Jis bhi desh ne phele supply di, deal done!
//Emergency oil supply
const russiaSupply = new Promise((resolve, reject) => {
setTimeout(() => reject("Russia: Cannot supply due to international sanctions"), 3000);
});
const saudiSupply = new Promise((resolve) => {
setTimeout(() => resolve("Saudi Arabia: 500k barrels ready for delivery!"), 1000);
});
const uaeReserves = new Promise((resolve) => {
setTimeout(() => resolve("UAE: Internal reserves available for use"), 2000);
});
Promise.any([russiaSupply, saudiSupply, uaeReserves])
.then((result) => {
console.log("Oil secured:", result);
// Output: "Oil secured: Saudi Arabia: 500k barrels ready for delivery!"
// Saudi Arabia responded in 1 second — the fastest!
})
.catch((error) => {
console.log("No supply available from anyone:", error);
});
Important thing to learn in promise.any()
The first to fulfill wins, all rejections are silently ignored
Only fails when all promises reject, giving you an Error
Use this when you have multiple fallback options and any one success is enough
Promise.race() - First to Finish Wins, Win or Lose
Promise.race() takes an array of promises. Whichever promise settles first - fulfilled or rejected, that result wins. The rest are ignored.
There is a key difference form Promise.any() which is race() does not care if the first settler is a failure. Jo bhi phele aaye be it resolve or reject vahi result hota hai.
Global Tension with help of promise.race()
The Iran Nuclear Crises - Who Acts first?
USA is in talks with Iran regarding settling the issues between Israel and Iran. Israel is preparing its military strike faster. The world will respond to whoever makes their move first, whether it results in peace deal or an airstrike. Phela action matter krta hai, chahe accha ho ya bura.
// Iran nuclear action
const usaDiplomacy = new Promise((resolve) => {
setTimeout(() => resolve("USA: Diplomatic talks initiated, 6-month framework"), 5000);
});
const israelAction = new Promise((resolve) => {
setTimeout(() => resolve("Israel: Preemptive strike on nuclear facilities executed"), 2000);
});
const iranBreakout = new Promise((_, reject) => {
setTimeout(() => reject("Iran: Nuclear enrichment threshold crossed"), 3000);
});
Promise.race([usaDiplomacy, israelAction, iranBreakout])
.then((result) => {
console.log("First move made:", result);
// Output: "First move made: Israel: Preemptive strike..." (arrived in 2s)
})
.catch((error) => {
console.log("Crisis first:", error);
});
IMP: race() also works on rejection:
const slowPeaceDeal = new Promise((resolve) => {
setTimeout(() => resolve("✅ Peace treaty signed"), 5000);
});
const fastWarDeclaration = new Promise((_, reject) => {
setTimeout(() => reject("💥 War declared"), 500);
});
Promise.race([slowPeaceDeal, fastWarDeclaration])
.catch((error) => {
console.log(error); // "💥 War declared" — settled first at 500ms
});
Important thing to learn in promise.race()
Immediately settles with that rejection
First rejection's error
Need the absolute fastest result
Promise.resolve() - Create an already resolved promise
Promise.resolve(value) returns a promise that is already in the fulfilled state with the given value. No waiting, No async - its instantly resolved. Useful when we need to wrap a plain value in a promise format.
We use this we we need to resolve the promise immediately.
Global Tension with help of promise.resolve()
USA has already prepared, signed and sealed a disaster aid document. Jab bhi koi country aye, no process is needed, its a done deal, ready to go immediately, no negotiations no waiting.
// Pre-approved disaster aid — instantly available
const preApprovedAid = Promise.resolve({
from: "USA",
amount: "$500 million",
status: "Pre-approved, unconditional",
deliveryTime: "Immediate"
});
preApprovedAid.then((aid) => {
console.log("Aid package details:", aid);
// Executes immediately — no async delay at all
});
Important thing to learn in promise.resolve()
Creates an instantly resolved promise - no async involved
Great for normalizing values in functions that sometimes return plain values and sometimes return promises
Promise.reject() - Create an Already-Rejected Promise
Promise.reject(reason) returns a promise that is already in the rejected state with the given reason. Its similar to Promise.resolve() but it works only on reject state. Commonly used for predicting error flows and testing.
Global Tension with help of promise.reject()
In the UN Council, Russia sometimes announces the rejection even before the vote has began. They veto any resolution which is going to be passed. That's a pre-rejected promise. Koi bhi argument ya outcome change nai kr skta.
// Russia's veto — pre-announced, non-negotiable
const russiaVeto = Promise.reject(
new Error("Russia: Vetoing Ukraine resolution — no conditions will change this")
);
russiaVeto
.then(() => {
console.log("Resolution passed"); // This will NEVER run
})
.catch((error) => {
console.log("Veto applied:", error.message);
// Output: "Veto applied: Russia: Vetoing Ukraine resolution..."
});
Promise.try() - Catch Synchronous Errors Inside Promise
Promise.try() is a new method. It takes a function, executes it, and wraps the result in the a promise. If the function throws error, that error is also caught and converted into a rejected promise, instead or crashing.
Kabhi kabhi function sync hota ya async Promise.try() ensure krta hai ki Error bhi properly promise mai convert hojaye.
Global Tension with help of promise.try()
Ho sakta hai ki Situation normal ho ya crises ki, dono ko handle krna hai.
Promise.try(() => {
return "Diplomatic meeting started";
}).then(console.log);
//Agar Error aaya to
Promise.try(() => {
throw new Error("Conflict started");
}).catch(console.log);
Promise.withResolvers() - Extract the Controls Outside the Promise
Promise.withResolvers() returns an object with three things: { promise, resolve, reject }. Yeh tab useful hai jab aapko promise ko kahin aur se resolve/reject karna ho, promise create karne ki jagah se alag.
Promise.withResolvers() lets you create a promise and hand out its resolve/reject controls to whoever needs them — instead of being locked inside the constructor.
const { promise, resolve, reject } = Promise.withResolvers();
// India and Pakistan both have the power to decide
setTimeout(() => resolve(" India accepted the ceasefire!"), 1000);
setTimeout(() => reject(" Pakistan rejected the ceasefire!"), 2000);
// UN just waits for whoever decides first
promise
.then((msg) => console.log("Peace:", msg))
.catch((err) => console.log("Crisis:", err));
// Output: Peace: India accepted the ceasefire!
// Pakistan's rejection at 2s is ignored — promise already settled ✅
Here, the UN creates the framework, India and Pakistan each hold a trigger, but the moment India resolves it at 1s, the promise is sealed. Pakistan's rejection at 2s arrives too late and is completely ignored.
Which method should be used when?
Conclusion
JavaScript Promises are one of the most powerful tools for managing asynchronous code. And just like real-world diplomacy and conflict, kabhi sab ki agreement zaroori hoti hai (Promise.all), kabhi sirf ek ka succeed karna kaafi hota hai (Promise.any), kabhi pehla action matter karta hai chahe accha ho ya bura (Promise.race), aur kabhi aapko complete picture chahiye bina kisi ko miss kiye (Promise.allSettled). Filhaah to yahi important methods hai.




