Skip to main content

Command Palette

Search for a command to run...

Async JavaScript Demystified: Promises & Their Methods

Updated
β€’5 min read
Async JavaScript Demystified: Promises & Their Methods

What is Async ?

Lets first discuss what is async means ??

Async nature or async operation means any task which starts now but it doesn't completes immediately , it takes sometime to complete that tasks . But We don't want to wait for the task to complete . We kind of let it run in background and resume other tasks.

We have same async analogy is in JavaScript which is handled by promise .

Why we need Promise in JavaScript ?

Well before promise , We were handling this async task using callback function in JavaScript .
It worked fine technically but the simplicity of the code was not there . It was so much complex when you have multiple callback func. basically We called that callback hell . It was so much difficult to debug or even read the code .

bookTrain(() => {
    console.log("Train has booked")
  bookHotel(() => {
        console.log("hotel booking confirmed")
    bookCab(() => {
            console.log("Cab booked ")
      planSightseeing(() => {
        console.log("Trip planned πŸŽ‰");
      });
    });
  });
});

Then JS developers introduced Promise concept in ES6 . It really helped developers to handle multiple async tasks really in easy way . Promises solve this callback hell problem by providing a cleaner, more manageable way to handle asynchronous operations.

They allow you to chain operations together and handle errors more gracefully.

bookTrain()
  .then(() => bookHotel())
  .then(() => bookCab())
  .then(() => planSightseeing())
  .then(() => {
    console.log("Trip planned πŸŽ‰");
  })
  .catch(() => {
    console.log("Something went wrong ❌");
  });

promise has different states how it handles to let the main thread know if the async task is in which state ? is it completed , having error

Different states of Promises :

In JavaScript Promise We have states

  1. Pending : This is the default state whenever a promise is created , it just started to work, but didn't finished yet

  2. Resolved : When the async task is completed or fulfilled with all its components , then promise change it's state to resolved . using then() we handle promise resolved status .

  3. Rejected : Lets say there is some error while performing the async task then the state of promise changed to rejected or errored out , using catch() we handle rejected status

How a promise works behind the scenes

1. Call Stack & Promise Creation :

JavaScript runs code synchronously using the Call Stack (one task at a time). When a Promise is created, its executor function runs immediately on the call stack. The Promise starts in the pending state and moves to fulfilled (resolve) or rejected (reject) once settled. Importantly, calling resolve() or reject() does not execute .then() or .catch() right away.

2. Microtask Queue & Promise Callbacks

Promise callbacks (then, catch, finally) are placed into the Microtask Queue. The Microtask Queue has higher priority than the normal callback (macrotask) queue. Even if a Promise resolves immediately, its handlers wait until the call stack becomes empty. This is why Promise callbacks always run after synchronous code, but before setTimeout or events.

3. Event Loop & Execution Order

The Event Loop continuously checks whether the Call Stack is empty.Once empty, it executes all Microtasks first (Promises). Only after the Microtask Queue is completely drained does it execute one task from the Callback Queue. This mechanism makes Promises feel asynchronous while keeping JavaScript single-threaded and predictable.

Promise Methods ( Expand Each to know more ) :

  1. Promise.all() -->

    Promise.all() takes an array of Promises and returns a single Promise that resolves when all input Promises have resolved successfully.

    If any Promise in the array rejects, Promise.all() immediately rejects with that error.


    Example :
    Becoming an IPS officer requires clearing all stages:
    Prelims
    mains
    Interview

    ❌ Fail one β†’ selection failed
    βœ… Clear all β†’ success

    Promise.all([prelims, mains, interview])
      .then(() => console.log("Selected as IPS"))
      .catch(() => console.log("Better luck next attempt"));
  2. Promise.any() -->

    Promise.any() takes an array of Promises and returns a single Promise that resolves whenever any single input Promises have resolved successfully.

    If any of the input promises not resolved then it sends error

    Example :
    You apply to 5 companies.
    You only need ONE offer to be happy πŸ˜„
    Doesn’t matter how many reject you.

    Promise.any([companyA, companyB, companyC])
      .then(job => console.log("Got job at", job))
      .catch(() => console.log("All applications rejected"));
  3. Promise.allSettled() -->

    Promise.allSettled() simply means Everyone’s Result Matters whether its resolved or rejected . It Waits for all promises to finish . Returns result of

    each promise (success or failure)


    Example :
    Nick Fury assigns a mission to the Avengers:

    Iron Man β†’ hack the system

    Thor β†’ stop the alien invasion

    Hulk β†’ smash enemy base

    Hawkeye β†’ provide cover fire

    Some succeed, some fail β€” but Fury wants a full report of every Avenger, not just the winners.

    const ironMan = Promise.resolve("Hack successful");
    const thor = Promise.reject("Hammer malfunction");
    const hulk = Promise.resolve("Base destroyed");
    const hawkeye = Promise.reject("Out of arrows");
    

    Promise.allSettled([ironMan, thor, hulk, hawkeye])
    .then(results => console.log(results));

  4. Promise.race() -->

    Promise.race() takes an array of Promises and returns a single Promise that settled first of all the promises . It doesn't wait for others . Whoever settled first it sends that promise immediately . that promise can give resolved or reject .


    Example :
    Multiple cars start together πŸš—πŸš™πŸš•
    The first car to reach the finish line wins,
    others don’t matter.

    Promise.race([car1, car2, car3])
      .then(winner => console.log("Winner:", winner));

Final Thoughts

Each Promise method solves a different real-world problem:

all() β†’ everything must succeed
any() β†’ one success is enough
allSettled() β†’ show all outcomes
race() β†’ first result wins
resolve() / reject() β†’ instant state

Until next blog , keep hustling to be busy πŸ’ͺπŸ’ͺ

β€œLearning JS is a lot of fun . I’m on the same path as you. If you want to learn together β€”

Continue this journey with me @coder_debπŸš€β€

javascript promise and methods