Promises & its Properties
🔹 What is a Promise?
Section titled “🔹 What is a Promise?”- A
Promiseobject represents the eventual completion (or failure) of an asynchronous operation & its resulting value. - A Promise is an object that represents a value that may be:
- Pending -> operation not finished yet.
- Fulfilled -> operation completed successfully.
- Rejected -> operation failed.
- Eg:
const promise = new Promise((resolve, reject)=>{ setTimeout(()=> resolve("Success!"), 1000) })
promise.then(res=> console.log(res)).catch((err)=> {console.log(err)})🔹 Key Promise Static Methods (Properties)
Section titled “🔹 Key Promise Static Methods (Properties)”-
Promise.all(iterable)
- Runs promise in parallel.
- Resolves only if all succeed, rejects if all fails.
- Eg:
Promise.all([Promise.resolve(1), Promise.resolve(2)]).then(res=> console.log(res)) // [1,2]
-
Promise.allSettled(iterable)
- Waits for all promise to settle(fulfilled or rejected).
- Always return array with
{status, value/reason}. - Eg:
Promise.allSettled([Promise.resolve(1), Promise.reject('Err')]).then(res=> console.log(res))// [ {status:"fulfilled", value:1}, {status:"rejected", reason:"Err"} ]
-
Promise.any(iterable)
- Resolves as soon as any one succeeds.
- Rejects only if all fails.
- Eg:
Promise.any([Promise.reject("fail"), Promise.resolve("win")]).then(res => console.log(res)); // "win"
-
Promise.race(iterable)
- Resolves/rejects with the first promise that settles (success or failure).
- Eg:
Promise.race([new Promise(res=> setTimeout(()=> res('fast'), 100)),new Promise(res=> setTimeout(()=> res('slow'), 1000)),]).then(res=> console.log(res)) // "fast"
🔹 Instance Methods
Section titled “🔹 Instance Methods”.then(onFulFilled)-> runs on success..catch(onRejected)-> runs on failure..finally(onFinally)-> always runs after completion (success or failure).- Eg:
promise .then(res => console.log(res)) .catch(err => console.error(err)) .finally(() => console.log("Done!"));🔹 Summary Table
Section titled “🔹 Summary Table”| Method | Behavior |
|---|---|
Promise.all | All must succeed, else reject |
Promise.allSettled | Returns result of all (fulfilled/rejected) |
Promise.any | Resolves on first success |
Promise.race | Resolves/rejects on first finished |
.then() | Handle success |
.catch() | Handle failure |
.finally() | Always run after completion |
👉 Quick memory hook:
Section titled “👉 Quick memory hook:”- all = “everyone must win”
- allSettled = “give me the report card”
- any = “just one winner is enough”
- race = “whoever finishes first wins (success or fail)”