Javascript Promises: ChaiCode Editition

What are Promises?
Promise is exactly same as the favourite line of Hitesh Choudhary sir,
Areyy ruko ruko thamba thamba jra....."
Technically which means, promise is an affirmation from the javascript which assures the execution of the operation, whether it be a success or failure will be informed after the result is received from asynchronous operation.
Asynchronous operations- operations that are run independently of the main program flow, thus allowing other program code to execute.
Why is it used?
In the Ecma Script(ES6) edition the concept of promise was introduced.
Before promises developers used to rely on callbacks to handle the asynchronous operations.
Callbacks do handle the async operations but they often led to deeply nested code known as "callback hell".
Promises provide a much more organised and manageable method for handling the async operations.
Promise States:
Similar to the real life promise, a promise in javascript can be in any one of the three states:
1)Pending: This is the state where the promise is created, also the asynchronous operation has not yet completed.
2)Fulfilled: In this state the promise is successfully completed. The result value can be accessed. It triggers the .then().
3. Rejected: The operation has failed, a error message for it is available.
A promise always starts as Pending.
Once a promise is settled, it becomes immutable.(Similar to Bigbossji ka aadesh)
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Data fetched!");
} else {
reject("Something went wrong.");
}
});
myPromise
.then(value => console.log(value)) // "Data fetched!" (resolve)
.catch(err => console.error(err)) // "Something went wrong."(error)
.finally(() => console.log("Done")); // "Done"
Output:
Data fetched!
Done
Promise Methods:
Promise.any()
-Promise.any is exactly same as Piyush sir.
Bas ladki haa krde varnamala leke ready khada hu turant pehena dunga
Agar koi bhi "haa" naa kare toh apna kya hai pehle bhi single the phir rehlenge
-Takes an array of Promises and returns a single Promise that resolves as soon as any of the input Promise is fulfilled.
-Returns the first fulfilling promise. If all are rejected then returns a object of arrays containing arrays of rejection reasons.
Code Example
//Example 1: User login from multiple auth providers
const googleLogin = new Promise((resolve, _) => {
setTimeout(() => resolve("Google auth failed"), 700);
});
const githubLogin = new Promise((resolve) => {
setTimeout(() => resolve("Logged in with GitHub ✅"),500);
});
const facebookLogin = new Promise((_, reject) => {
setTimeout(() => reject("Facebook auth failed"), 300);
});
Promise.any([googleLogin, githubLogin, facebookLogin])
.then(result => console.log(result))
.catch(err => console.error("All logins failed:", err));
//Example 2:Multiple `Payment gateways
const razorpay = new Promise((_, reject) => {
setTimeout(() => reject("Razorpay server down"), 1000);
});
const stripe = new Promise((_, reject) => {
setTimeout(() => reject("Stripe payment failed"), 700);
});
const paypal = new Promise((_, reject) => {
setTimeout(() => reject("PayPal connection timeout"), 500);
});
Promise.any([razorpay, stripe, paypal])
.then(result => console.log("Payment successful:", result))
.catch(err => console.error("All payments failed:", err));
Output:
Logged in with GitHub ✅
All payments failed: [AggregateError: All promises were rejected] {
[errors]: [
'Razorpay server down',
'Stripe payment failed',
'PayPal connection timeout'
]
}
Code Explanation:
User login with multiple auth providers
- Despite the fact that facebook login takes the least time, github login is the one which is the first successful promise.
Multiple Payment gateways
.then() is never reached
.catch()gets tiggered with Aggregate Error— meaning every option was exhausted.
Promise.race()
-Promise.race() is exactly same as Times Arena leaderboard.
The first one in the leaderboard gets the goodies,he will be able to receive the parcel or not has no affect.
-takes an array of Promises and returns a single Promise that resolves or rejects as soon as the first Promise in the array settles.
Code Example
//Example 1: First server to respond
const server1 = new Promise((resolve, reject) => {
setTimeout(() => resolve("Response from Server 1 ✅"), 1000);
});
const server2 = new Promise((resolve, reject) => {
setTimeout(() => resolve("Response from Server 2 ✅"), 500);
});
const server3 = new Promise((resolve, reject) => {
setTimeout(() => reject("Server 3 crashed ❌"), 800);
});
Promise.race([server1, server2, server3])
.then(result => console.log("Winner:", result))
.catch(err => console.error("First settled was a failure:", err));
//Example 2: The First server to crash
const server1 = new Promise((_, reject) => {
setTimeout(() => reject("Server 1 crashed ❌"), 1000);
});
const server2 = new Promise((_, reject) => {
setTimeout(() => reject("Server 2 crashed ❌"), 500);
});
const server3 = new Promise((_, reject) => {
setTimeout(() => reject("Server 3 crashed ❌"), 800);
});
Promise.race([server1, server2, server3])
.then(result => console.log("Winner:", result))
.catch(err => console.error("First to crash:", err));
Output:
Winner: Response from Server 2 ✅
First to crash: Server 2 crashed ❌
Code Explanation:
As seen in the examples the resolve or reject has no affect on the settlement of the promise. The only thing that is considered is the first promise to settle, which in both the cases is server 2 because of the set timeouts.
Promise.allSettled()
-Promise.allSettled() is exactly same as Hitesh sir quotes,
Understanding each and every concept in the lecture itself is not necessary.
Attending the live lectures consistently despite of result is what actually matters.
-it waits for all Promises to settle (either resolve or reject) and returns the results of all of them, regardless of whether they succeeded or failed.
Code Example
const order1 = new Promise((resolve) => {
setTimeout(() => resolve("Order 1 delivered ✅"), 1000);
});
const order2 = new Promise((_, reject) => {
setTimeout(() => reject("Order 2 cancelled ❌"), 500);
});
const order3 = new Promise((resolve) => {
setTimeout(() => resolve("Order 3 delivered ✅"), 800);
});
const order4 = new Promise((_, reject) => {
setTimeout(() => reject("Order 4 out of stock ❌"), 600);
});
Promise.allSettled([order1, order2, order3, order4])
.then(results => {
results.forEach(result => {
if (result.status === "fulfilled") {
console.log("Success:", result.value);
} else {
console.log("Failed:", result.reason);
}
});
});
Output:
Success: Order 1 delivered ✅
Failed: Order 2 cancelled ❌
Success: Order 3 delivered ✅
Failed: Order 4 out of stock ❌
Code Explanation:
In the above example, despite the result only thing that matters is the completion and not the outcome of it.
Promise.all()
-Promise.all() is same as the multi correct quiz question on Masterji.
Marks for Multi correct questions are only given if all the correct answers are selected.
Even if one correct answer is not selected then marks are not given.
-returns a fulfilled promise only if all promises are fulfilled along with an array of fulfilment value.
-even if one input promise is rejected, a reject is immediately returned.
Code Example
//Example 1: Loading data needed for dashboard
const getUsers = new Promise((resolve) => {
setTimeout(() => resolve("Users loaded ✅"), 1000);
});
const getPosts = new Promise((resolve) => {
setTimeout(() => resolve("Posts loaded ✅"), 800);
});
const getComments = new Promise((resolve) => {
setTimeout(() => resolve("Comments loaded ✅"), 600);
});
Promise.all([getUsers, getPosts, getComments])
.then(results => {
console.log(results[0]);
console.log(results[1]);
console.log(results[2]);
})
.catch(err => console.error("Something failed:", err));
//Example 2:
const getUsers = new Promise((resolve) => {
setTimeout(() => resolve("Users loaded ✅"), 1000);
});
const getPosts = new Promise((_, reject) => {
setTimeout(() => reject("Posts server down ❌"), 800);
});
const getComments = new Promise((resolve) => {
setTimeout(() => resolve("Comments loaded ✅"), 600);
});
Promise.all([getUsers, getPosts, getComments])
.then(results => {
console.log(results[0]);
console.log(results[1]);
console.log(results[2]);
})
.catch(err => console.error("Something failed:", err));
Output:
Users loaded ✅
Posts loaded ✅
Comments loaded ✅
Something failed: Posts server down ❌
Code Explanation:
In the first example all the three, that is users, posts and comments are loaded and so the promise returns fullfilled.
In the second example the server for posts was down and so promise immediately returns rejected that is error.
Promise.resolve()
-Promise.resolve() is exactly same as our (hunhaar) TA MR. NIKHIl Sir,
resolves the questions immediately with a value
- it is a static method that creates a Promise that is immediately resolved with a given value. It's a shorthand for creating a Promise that's already in the fulfilled state.
Code Example
// Example 1: Promise that is immediately resolved
const instantPromise = Promise.resolve("Already resolved!");
instantPromise.then(value => {
console.log(value);
});
// Example 2: To convert values into Promises
const number = Promise.resolve(33);
number.then(value => {
console.log(`The answer is: ${value}`);
});
Output:
I'm already resolved!
The answer is: 33
Code Explanation:
The first example creates a Promise that is already in the fulfilled state with the value "Already resolved!".
When.then() is called, it immediately executes with that value.
Promise.reject()
-Promise.reject() is exactly same as our (hunhaar) TA MR. AKASH Sir,
rejects the questions immediately with a value.
-It creates a Promise that is immediately rejected with a given reason. This is useful when you want to signal an error or failure condition right away.
Code Example
// Example 1: Immediately rejected promise
const rejectedPromise = Promise.reject("Access denied!");
rejectedPromise
.then(value => {
console.log(value);
})
.catch(error => {
console.log(`Error: ${error}`);
});
Output:
Error: Access denied!
Code Explanation:
The example creates a Promise that is already in the rejected state with the value "Already resolved!".
When.catch() is called, it immediately executes with that value.



