JavaScript

Handle asynchronous tasks cleanly with Promise states, chaining, error handling, and combinator methods.

Promises in Simple Terms

A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. It replaces messy nested callback functions ("Callback Hell") with clean, chainable logic.

💡 Real-World Analogy: The Food Court Buzzer Token

When you order a meal at a fast-food counter, the cashier gives you a vibrating buzzer token:

  • Pending: You hold the token while the chef cooks. You don't have food yet, but you have a guarantee.
  • Fulfilled (Resolved): The buzzer beeps green! You pick up your meal at the counter (.then()).
  • Rejected: The buzzer beeps red because the ingredients ran out (.catch()).
  • Settled: Once resolved or rejected, the promise is done and its state never changes.

Creating & Consuming a Promise

Use new Promise((resolve, reject) => { ... }) to wrap any async operation:

function fetchScore(playerName) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (playerName) resolve({ player: playerName, score: 98 });
            else reject(new Error("Missing player name!"));
        }, 100);
    });
}

fetchScore("Aman")
    .then(data => {
        console.log("Score received:", data.player, "scored", data.score);
        return data.score + 10;
    })
    .then(bonusScore => console.log("With bonus points:", bonusScore))
    .catch(err => console.error("Fetch failed:", err.message))
    .finally(() => console.log("Promise settled completely."));
Output
Score received: Aman scored 98
With bonus points: 108
Promise settled completely.

The 4 Essential Promise Combinators

When dealing with multiple promises concurrently, JavaScript provides 4 battle-tested static methods:

01

Promise.all()

All or Nothing: Resolves when ALL promises resolve; fails fast immediately if ANY single promise rejects.

02

Promise.allSettled()

Never Fails: Waits for ALL promises to finish regardless of success or failure. Returns status objects.

03

Promise.race()

Fastest Finisher: Settles as soon as the FIRST promise resolves OR rejects.

04

Promise.any()

First Success: Resolves as soon as the FIRST promise resolves. Ignores rejections unless all reject.

🎯 Promises Interview Deck
Question 1 of 5
JavaScript Interview PuzzleQ1 of 5
Promise.resolve(2)
    .then(x => x * 2)
    .then(x => x + 4)
    .then(x => console.log("Final:", x));
What will be logged to the console?
JavaScript Interview PuzzleQ2 of 5
const p1 = Promise.resolve("A");
const p2 = Promise.reject("Error B");
const p3 = Promise.resolve("C");

Promise.all([p1, p2, p3])
    .then(res => console.log("Success:", res))
    .catch(err => console.log("Caught:", err));
What will be printed?
JavaScript Interview PuzzleQ3 of 5
const p1 = Promise.resolve(10);
const p2 = Promise.reject("Boom");

Promise.allSettled([p1, p2]).then(results => {
    console.log(results[0].status, results[1].status);
});
What will be logged?
JavaScript Interview PuzzleQ4 of 5
const p1 = new Promise((_, rej) => setTimeout(() => rej("Fast Error"), 50));
const p2 = new Promise(res => setTimeout(() => res("Slow Success"), 150));

Promise.race([p1, p2])
    .then(val => console.log("Won:", val))
    .catch(err => console.log("Lost:", err));
What will be output by Promise.race?
JavaScript Interview PuzzleQ5 of 5
const p1 = Promise.reject("First fail");
const p2 = Promise.resolve("Second");
const p3 = Promise.resolve("Third");

Promise.any([p1, p2, p3]).then(val => {
    console.log("Winner:", val);
});
What will be logged by Promise.any?

Hands-On Practice: Build a Sleep Delay Helper

Implement a function delay(ms) that returns a Promise which resolves with the message "Done waiting [ms]ms" after ms milliseconds.