JavaScript Promise

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
To learn about the way promises work and how you can use them, we advise you to read Using Promises first.
Here is the advanced defination of the js promise :
A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
Now here we learn about the js promise by example (Tumhare gf ki khani ) :
JavaScript Promises samajhne ka easiest way hai --> Girlfriend analogy.
A Promise is like your girlfriend sending:
“We need to talk.”
You don’t know what it means yet.
It could be:
🥰 “I have a surprise for you”
😤 “You forgot our anniversary”
So instead of giving you the result immediately, she gives you suspense.
That suspense = Promise
Promise States (Relationship Drama)
Pending:
She hasn’t replied yet.
Message sent. Double tick. No blue tick.
You are overthinking.
Fulfilled:
She replies:
“I miss you ”
Success. Life is beautiful.
Rejected:
She replies:
“We need space.”
Error. System crash. Emotional damage.
Promise ek object hai jo represent karta hai future ka result.;
Sabse pehle basic Promise samajhte hain :
const gfPromise = new Promise((resolve, reject) => {
const mood = "good";
if (mood === "good") {
resolve("GF is coming ❤️");
} else {
reject("GF is not coming 😭");
}
});
gfPromise
.then(result => console.log(result))
.catch(error => console.log(error));
Step-by-step explanation
Step 1: Promise create hua
const gfPromise = new Promise(...)
Yeh GF se question poochne jaisa hai.
Step 2: resolve and reject kya hai
(resolve, reject)
These are functions.
resolve --> success
reject --> failure
Step 3: condition check hui
if (mood === "good")
Agar GF ka mood good hai --> resolve
warna --> reject
Step 4: then() runs on success
.then(result => console.log(result))
Output:
GF is coming ❤️
Step 5: catch() runs on failure
.catch(error => console.log(error))
Output:
GF is not coming 😭
Iske aagee hum Promise ke sabhee Methods padte hai :
1. Promise.resolve()
Tumhari life ki kahani : Tum GF ko call karte ho,
wo bolti hai:
"Main already bahar hoon ❤️"
No waiting needed.
Code :
const gfPromise = Promise.resolve("GF already outside ❤️");
console.log(gfPromise);
Output:
Promise { fulfilled: "GF already outside ❤️" }
Use then()
gfPromise.then(result => {
console.log(result);
});
Output:
GF already outside ❤️
Explanation : Promise.resolve() creates instantly successful promise.
2. Promise.reject()
Tumhari life ki kahani : GF bolti hai:
"Papa ghar pe hain 😭"
Immediate rejection.
Code
const gfPromise = Promise.reject("GF cannot come 😭");
gfPromise.catch(error => {
console.log(error);
});
Output:
GF cannot come 😭
3. Promise.all()
Tumhari life ki kahani : Tum GF ko bolte ho bring:
chocolate
hug
kiss
Tumhe sab chahiye.
Code :
const chocolate = new Promise(resolve => {
setTimeout(() => resolve("Chocolate ❤️"), 2000);
});
const hug = new Promise(resolve => {
setTimeout(() => resolve("Hug 🤗"), 1000);
});
const kiss = new Promise(resolve => {
setTimeout(() => resolve("Kiss 😘"), 3000);
});
Promise.all([chocolate, hug, kiss])
.then(results => {
console.log(results);
});
Output after 3 sec:
["Chocolate ❤️", "Hug 🤗", "Kiss 😘"]
Explanation
Promise.all waits for ALL promises. even if one fails --> everything fails.
4. Promise.allSettled()
Tumhari life ki kahani : GF brings:
chocolate 👍
hug ❌
kiss 👍
Tumhe full report milta hai.
Code :
const chocolate = Promise.resolve("Chocolate ❤️");
const hug = Promise.reject("No hug 😡");
Promise.allSettled([chocolate, hug])
.then(results => {
console.log(results);
});
Output:
[
{ status: "fulfilled", value: "Chocolate ❤️" },
{ status: "rejected", reason: "No hug 😡" }
]
5. Promise.race()
Tumhari life ki kahani : Tum GF ko text karte ho:
"Reply fast please"
Jo pehle reply kare --> winner
Code :
const slowReply = new Promise(resolve => {
setTimeout(() => resolve("Reply after 5 sec"), 5000);
});
const fastReply = new Promise(resolve => {
setTimeout(() => resolve("Reply after 1 sec ❤️"), 1000);
});
Promise.race([slowReply, fastReply])
.then(result => {
console.log(result);
});
Output:
Reply after 1 sec ❤️
6. Promise.any()
Tumhari life ki kahani : Tum 5 baar call karte ho.
Ek baar pick kar liya --> success.
Code :
const call1 = Promise.reject("Busy");
const call2 = Promise.reject("Busy again");
const call3 = Promise.resolve("Picked call ❤️");
Promise.any([call1, call2, call3])
.then(result => {
console.log(result);
});
Output:
Picked call ❤️
Promise instance methods :
1. .then() Runs when Promise is SUCCESSFUL
Tum GF se poochte ho:
"Milne aaogi?"
GF bolti hai:
"Haan aa rahi hoon ❤️"
Tab tum kya karoge?
1. Ready ho jaoge.
2. Happy ho jaoge.
That reaction = .then()
Promise.resolve("GF arrived ❤️")
.then(result => {
console.log(result);
});
Output:
GF arrived ❤️
Step-by-step flow :
Promise created
Promise resolved
then() runs
Here is an async example if you want to see that :
const gfPromise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("GF arrived after 2 seconds ❤️");
}, 2000);
});
gfPromise.then(function(result) {
console.log(result);
});
Output after 2 sec:
GF arrived after 2 seconds ❤️
2. .catch() Runs when Promise FAILS
GF bolti hai:
"Main nahi aa sakti 😭"
Tab tum sad ho jaate ho.
That reaction = .catch()
Syntax :
promise.catch(onError)
Example :
const gfPromise = new Promise(function(resolve, reject) {
setTimeout(function() {
reject("GF didn't come 😭");
}, 2000);
});
gfPromise.catch(function(error) {
console.log(error);
});
Output:
GF didn't come 😭
catch() receives the error :
Promise.reject("Error happened")
.catch(function(error) {
console.log(error);
});
Output:
Error happened
3. .finally() Runs ALWAYS (success or fail)
GF aaye ya na aaye, tum gym toh jaoge hi.
That action = .finally()
It runs no matter what happens.
Syntax :
promise.finally(onFinally)
Example ( jo chaale ga hi )
Promise.resolve("GF came ❤️")
.finally(function() {
console.log("Going to gym 💪");
});
Output:
Going to gym 💪
Example :
Promise.reject("GF didn't come 😭")
.finally(function() {
console.log("Going to gym anyway 💪");
});
Output:
Going to gym anyway 💪
Here is full example code of all three instance promise :
const gfPromise = new Promise(function(resolve, reject) {
const mood = "bad";
if (mood === "good") {
resolve("GF came ❤️");
} else {
reject("GF didn't come 😭");
}
});
gfPromise
.then(function(result) {
console.log("SUCCESS:", result);
})
.catch(function(error) {
console.log("ERROR:", error);
})
.finally(function() {
console.log("This always runs 💪");
});
Output:
ERROR: GF didn't come 😭
This always runs 💪
Now here are the main docs of the JS Promise from mdn-web-docs :
what is Js promise :
A JavaScript Promise is an object representing the eventual outcome of an asynchronous operation. It acts as a placeholder for a value that is not available yet, allowing you to handle the results or errors of asynchronous tasks in a more structured and readable way than traditional callbacks.
A Promise is in one of these states:
pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation was completed successfully.
rejected: meaning that the operation failed.
The eventual state of a pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options occur, the associated handlers queued up by a promise's then method are called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.
A promise is said to be settled if it is either fulfilled or rejected, but not pending.
You will also hear the term resolved used with promises — this means that the promise is settled or "locked-in" to match the eventual state of another promise, and further resolving or rejecting it has no effect. The State and fates document from the original Promise proposal contains more details about promise terminology. Colloquially, "resolved" promises are often equivalent to "fulfilled" promises, but as illustrated in "States and fates", resolved promises can be pending or rejected as well. For example:
jsCopy
new Promise((resolveOuter) => {
resolveOuter(
new Promise((resolveInner) => {
setTimeout(resolveInner, 1000);
}),
);
});
This promise is already resolved at the time when it's created (because the resolveOuter is called synchronously), but it is resolved with another promise, and therefore won't be fulfilled until 1 second later, when the inner promise fulfills. In practice, the "resolution" is often done behind the scenes and not observable, and only its fulfillment or rejection are.
Static methods :
These methods are called directly on the Promise class itself (Promise.all(...)) and take an iterable (like an array) of promises as an argument.
Promise.all(iterable): Returns a single promise that fulfills when all of the input promises have fulfilled. It rejects immediately if any of the input promises reject.Promise.allSettled(iterable): Returns a single promise that fulfills after all of the input promises have settled (either fulfilled or rejected), with an array of objects describing the outcome of each promise.Promise.any(iterable): Returns a single promise that fulfills as soon as any of the input promises fulfills. If all promises reject, it rejects with anAggregateError.Promise.race(iterable): Returns a single promise that settles (fulfills or rejects) as soon as the first of the input promises settles.Promise.resolve(value): Returns aPromiseobject that is already resolved with the given value.Promise.reject(reason): Returns aPromiseobject that is already rejected with the given reason (error)
Instance Methods :
These methods are called on a specific promise instance (myPromise.then(...)) to attach handlers for when the promise is settled (fulfilled or rejected).
.then(onFulfilled, onRejected): Appends fulfillment (onFulfilled) and/or rejection (onRejected) handlers to the promise. It returns a new promise, which enables Promise Chaining..catch(onRejected): Appends only a rejection handler to the promise. It is essentially shorthand for.then(undefined, onRejected)and is the preferred way to handle errors at the end of a chain..finally(onFinally): Appends a handler function that is executed regardless of the promise's outcome (whether fulfilled or rejected). It's useful for cleanup operations, like hiding a loading spinner.
Here is an example of all methods of js promises in one code , it look difficult but once you understand it won't look difficult :
// Fake API function to simulate async work
function fakeAPI(name, delay, shouldFail = false) {
return new Promise((resolve, reject) => {
console.log(`Request started: ${name}`);
setTimeout(() => {
if (shouldFail) {
reject(`${name} failed `);
} else {
resolve(`${name} success `);
}
}, delay);
});
}
// Create promises
const p1 = fakeAPI("User API", 1000);
const p2 = fakeAPI("Post API", 2000);
const p3 = fakeAPI("Comment API", 1500, true);
/* INSTANCE METHODS */
// .then()
p1.then(result => {
console.log("then:", result);
})
// .catch()
.catch(error => {
console.log("catch:", error);
})
// .finally()
.finally(() => {
console.log("finally: User API finished");
});
/* STATIC METHODS*/
// Promise.resolve()
Promise.resolve("Instant success")
.then(res => console.log("resolve:", res));
// Promise.reject()
Promise.reject("Instant reject")
.catch(err => console.log("reject:", err));
// Promise.all() → fails if any fails
Promise.all([p1, p2])
.then(res => console.log("all:", res))
.catch(err => console.log("all error:", err));
// Promise.allSettled() → always returns all results
Promise.allSettled([p1, p2, p3])
.then(res => console.log("allSettled:", res));
// Promise.race() → first completed wins
Promise.race([p1, p2, p3])
.then(res => console.log("race:", res))
.catch(err => console.log("race error:", err));
// Promise.any() → first success wins
Promise.any([p3, p1, p2])
.then(res => console.log("any:", res))
.catch(err => console.log("any error:", err));
/* ADVANCED INSTANCE CHAINING */
fakeAPI("Payment API", 1200)
.then(res => {
console.log("step 1:", res);
return fakeAPI("Invoice API", 1000);
})
.then(res => {
console.log("step 2:", res);
return "Final Result";
})
.then(res => {
console.log("step 3:", res);
})
.catch(err => {
console.log("chain error:", err);
})
.finally(() => {
console.log("Chain finished");
});
Output:
Request started: User API
Request started: Post API
Request started: Comment API
Request started: Payment API
resolve: Instant success
reject: Instant reject
then: User API success
finally: User API finished
race: User API success
any: User API success
step 1: Payment API success
all: [ 'User API success ', 'Post API success ' ]
step 2: Invoice API success
step 3: Final Result
Chain finished
allSettled: [
{ status: 'fulfilled', value: 'User API success ' },
{ status: 'fulfilled', value: 'Post API success ' },
{ status: 'rejected', reason: 'Comment API failed ' }
]
What this code is doing : fakeAPI
It makes a Promise that:
Waits some time
Then either:
resolve() = “Yay success ”
reject() = “Oops failed ”
p1, p2, p3 :
p1= success after 1 secp2= success after 2 secp3= fails after 1.5 sec
Instance methods :
.then()= runs if success.catch()= runs if failure.finally()= runs no matter what
Think:
Success = then
Failure = catch
Always = finally
Static methods :
Promise.resolve()= instant successPromise.reject()= instant failurePromise.all()= all must succeedPromise.allSettled()= tell me everything (success + fail)Promise.race()= fastest winsPromise.any()= first success wins
Chaining :
One task finishes = starts next = then next = then next
Like:
Payment = Invoice = Done
That’s it.
Promises = “I will do this later… and tell you what happened.”
I take this code from chat gpt just to tell you how all the methods work at same time .
Conclusion:
Promise is trust.
It may give happiness (.then),
may give pain (.catch),
but it always gives closure (.finally).
Credit to - [MDN Web Docs ] [Google Website ] for the amazing docs.




