Skip to content

Promises & its Properties

  • A Promise object 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)”
    1. 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]
    1. 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"} ]
    1. 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"
    1. 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"
  • .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!"));
MethodBehavior
Promise.allAll must succeed, else reject
Promise.allSettledReturns result of all (fulfilled/rejected)
Promise.anyResolves on first success
Promise.raceResolves/rejects on first finished
.then()Handle success
.catch()Handle failure
.finally()Always run after completion
  • all = “everyone must win”
  • allSettled = “give me the report card”
  • any = “just one winner is enough”
  • race = “whoever finishes first wins (success or fail)”