Promise in JavaScript
In the real world, a promise is a written statement or spoken(vow) saying definitely that you will do or not do something.
A promise in JavaScript is an object that represents the eventual result (success or failure) of an asynchronous operation.It can be in one of three states: pending (still waiting), fulfilled (success), or rejected (failure).
How we use a promise in code ?
We usually handle promises with .then() and .catch():
.then()runs if the promise is successful (fulfilled)..catch()runs if it fails (rejected).let myPromise = new Promise((resolve, reject) => { if (taskSuccess) { resolve("Task fulfilled,Hurray!!!!"); } else { reject("Sorry, something went wrong : Task Rejected"); } }); //consuming the promise myPromise .then(result => console.log(result)) // Task fulfilled,Hurray!!!! .catch(error => console.log(error));//Sorry, something went wrong : Task Rejected
A real world example:
A person wants to start a new vegetarian restaurant.
His first priority is to get the best raw materials (vegetables) for his dishes.
He goes to a wholesale market near his town to check the raw materials for the restaurant.
He checks all the different shops in the market.
He compares the quality and price of vegetables at each shop.
He writes down the prices of high-quality vegetables in his diary.
After careful thinking, he concludes that one shop offers high-quality vegetables at an affordable price.
He selects that shop to supply him with the vegetables.
He negotiates the price for all vegetables.
He asks the shopkeeper to deliver vegetables daily starting from a specific date in the morning.
The shopkeeper gives him a receipt.
The receipt acts as a promise that the vegetables will be delivered.
Understanding the Promise Concept with the above process that has taken place:
At this stage, the restaurant owner does not have the vegetables yet , the promise is in a pending state.
The receipt is a guarantee that something will happen later.
If the vegetables arrive fresh and on time, the promise is fulfilled.
If the shopkeeper fails to deliver the vegetables, the promise is rejected.
function orderVegetables(time) {
return new Promise((resolve, reject) => {
console.log("Owner has placed order and received receipt from the Shopkeeper => (Promise is Pending)");
let shopkeeperDelivers = true; // let assume true for successful delivery
setTimeout(() => {
if (shopkeeperDelivers) {
resolve("Fresh vegetables delivered on time! (Promise Fulfilled)");
} else {
reject("Shopkeeper failed to deliver vegetables. (Promise Rejected)");
}
}, time); // delivery time => after 3 seconds deliver the vegetbales
});
}
orderVegetables(3000) //3000 is the time after which owner want vegetables to be delivered
.then((message) => {
console.log(message);
})
.catch((error) => {
console.log(error);
});
Explaination of what is happening in the code above:
When the restaurant owner calls the orderVegetable(3000) .
A new Promise object is created immediately
" Owner has placed order and received receipt from the Shopkeeper => (Promise is Pending) " is logged in the console immediately.
Right now the promise is in a pending state
setTimeout() starts a 3-second timer (asynchronous task), but JavaScript doesn't wait for the code inside it to execute immediately.
After 3 seconds:
It checks shopkeeperDelivers to be true,if it is ture then →
resolve()is called → Promise becomes Fulfilled →.then()runs.If shopkeeperDelivers to be false, the vegetable are not delivered →
reject()is called → Promise becomes Rejected →.catch()runs.
Concept of Promise.all() in Javascript
Promise.all() is used when a user wants to run multiple promises at the same time and wait until all of them finish successfully . Promise.all() takes an array of promises and returns a single new promise.
Real World Meaning: Let us extend our above example of a restaurant owner starting the restaurant; now he wants to add a fruit salad to the restaurant menu . He goes to the market, checks the quality and price of the fruits, but this time he orders fruits from multiple shops at the same time.
He says : “I will open my restaurant only if ALL shops deliver fruits successfully to the restaurant ”
If
All shops deliver fruits → ✅ Success, restaurant opens with the right menu, having the dishes.
Even ONE shop fails → ❌ Entire operation fails, and the restaurant doesn't open
let shop1 = Promise.resolve("Shop 1 delivered Mango");
let shop2 = Promise.resolve("Shop 2 delivered Banana");
let shop3 = Promise.resolve("Shop 3 delivered Orange");
let shop4 = Promise.resolve("Shop 4 delivered Pineapple");
let shop5 = Promise.resolve("Shop 5 delivered Grapes");
Promise.all([shop1, shop2, shop3, shop4, shop5])
.then((results) => {
console.log("All deliveries successful!.Restaurant opens !!");
console.log(results);
})
.catch((error) => {
console.log("One shopkeeper failed to deliver. Restaurant desn't opens ", error);
});
What happens in the above code:
All promises start together (parallel execution takes place).
If ALL promises fulfilled →
.then()runsIf ANY ONE of the promises rejects →
.catch()runs immediately
let us suppose on shops fails :
let shop1 = Promise.reject("Shop 1 failed to deliver fruit");
Even if others succeed → Promise.all() fails immediately.
Promise.any()
Promise.any() resolves as soon as one promise succeeds, and rejects only if all fail.
Real World Meaning: Let us extend above example -
At least one shop must deliver. The restaurant owner wants to give the complimentary chocolates to the customer. He says :-
"I don’t care who delivers but at least ONE shop must deliver the chocolates successfully."
let chocolateShop1 = Promise.reject("Shop 1 out of stock ❌");
let chocolateShop2 = Promise.resolve("Shop 2 delivered mango chocolates 🍫");
let chocolateShop3 = Promise.reject("Shop 3 closed ❌");
Promise.any([chocolateShop1, chocolateShop2, chocolateShop3])
.then((result) => {
console.log("At least one shop delivered.Every customer will get complimentary chocolate");
console.log(result);
})
.catch((error) => {
console.log("All shops failed.Sorry ,no Chocolates ", error);
});
What happens in the above code :
Shop 1 is out of stock→ Rejected ❌
Shop 2 → Resolved ✅
Shop 3 is closed → Rejected ❌
Even though two promises failed in the above code,Promise.any() ignores failures until all promises fail
If ALL promises fails then it throws:
All shops failed.Sorry ,no Chocolates AggregateError: All promises were rejected
Promise.allSettled()
Promise.allSettled() waits for all promises to finish and returns their results, whether fulfilled or rejected.
Real World Meaning: Let us take the above example of the restaurant giving a complimentary chocolate to the customers.
Owner says:
Even if Some shops succeed in delivering the chocolate or some shops fail to deliver , he wants the final report.
let chocolateShop1 = Promise.reject("Shop 1 out of stock ❌");
let chocolateShop2 = Promise.resolve("Shop 2 delivered mango chocolates 🍫");
let chocolateShop3 = Promise.reject("Shop 3 closed ❌");
Promise.allSettled([chocolateShop1, chocolateShop2, chocolateShop3])
.then((results) => {
console.log("Final delivery report:");
console.log(results);
});
Output:
final delivery report:
[
{ status: "rejected", reason: "Shop 1 out of stock ❌" },
{ status: "fulfilled", value: "Shop 2 delivered mango chocolates 🍫" },
{ status: "rejected", reason: "Shop 3 closed ❌" }
]
Each result object has ,for success : { status: "fulfilled", value: "..." } ,
for failure : { status: "rejected", reason: "..." }
Note : " ... " represents the message when resolved or rejected
Summary Table :
| Method | Resolves When | Rejects When |
|---|---|---|
Promise.all() |
All succeed | One fails |
Promise.any() |
First success | All fail |
Promise.allSettled() |
Always resolves | Never rejects |
