Chapter 37 of 49

JavaScript Promises

When you order food at a busy restaurant counter, you don't get your food immediately. Instead, you get a token. That token is a promise: "Your food will be ready later." While you wait, you can sit down and talk to your friends. Eventually, one of two things happens:

  • Your number is called and you get your food. (Success)

  • They tell you the dish is sold out. (Failure)

A JavaScript Promise works the same way. In the previous chapter, we saw that callbacks get messy when async steps depend on each other (callback hell), and that errors are hard to handle. Promises solve both problems by giving us an object that represents a value that will be available in the future.


What is a Promise?

A Promise is an object that represents the eventual result of an asynchronous operation: either a value (success) or a reason it failed (error).

A promise is always in one of three states:

State

Meaning

Restaurant analogy

pending

The operation hasn't finished yet

You're holding the token, waiting

fulfilled

The operation succeeded, and the promise has a value

You got your food

rejected

The operation failed, and the promise has a reason (usually an Error)

The dish was sold out

                 ┌──► fulfilled (with a value)
pending ─────────┤
                 └──► rejected  (with a reason)

A promise that is either fulfilled or rejected is called settled. Once a promise settles, it can never change again. A fulfilled promise can't later become rejected, and vice versa.


Creating a Promise

We create a promise with new Promise(), passing it a function called the executor. The executor receives two functions: resolve (call it on success) and reject (call it on failure).

const orderFood = new Promise((resolve, reject) => {
    const available = true;

    setTimeout(() => {
        if (available) {
            resolve("Masala Dosa is ready!");
        } else {
            reject(new Error("Sorry, sold out."));
        }
    }, 1000);
});

console.log(orderFood);

Output:

Promise { <pending> }

When we log the promise right away, it is still pending, because the timer hasn't finished. The promise is like the token: it exists now, but the food doesn't yet.

The Executor Runs Immediately

One important detail: the executor function runs synchronously, right away, when the promise is created. Only the code that handles the result runs later.

console.log("Before");

const p = new Promise((resolve) => {
    console.log("Inside executor");
    resolve("Done");
});

p.then(value => console.log("Result:", value));

console.log("After");

Output:

Before
Inside executor
After
Result: Done

Even though the promise was resolved immediately, the .then() callback ran after "After". That's because promise callbacks are always run as microtasks, after the current code finishes, exactly as we saw in the event loop chapter.


Using a Promise: then(), catch(), and finally()

Creating promises is only half the story. Most of the time, you'll be consuming promises returned by other functions (like fetch()).

Method

Runs when...

.then(onFulfilled)

The promise is fulfilled. Receives the value.

.catch(onRejected)

The promise is rejected. Receives the reason (error).

.finally(onFinally)

The promise settles either way. Receives nothing. Good for cleanup.

function orderFood(dish, available, ms) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (available) {
                resolve(`${dish} is ready!`);
            } else {
                reject(new Error(`${dish} is sold out.`));
            }
        }, ms);
    });
}

orderFood("Masala Dosa", true, 500)
    .then(message => console.log("Success:", message))
    .catch(error => console.log("Failed:", error.message))
    .finally(() => console.log("Order 1 closed"));

orderFood("Idli", false, 1000)
    .then(message => console.log("Success:", message))
    .catch(error => console.log("Failed:", error.message))
    .finally(() => console.log("Order 2 closed"));

Output:

Success: Masala Dosa is ready!
Order 1 closed
Failed: Idli is sold out.
Order 2 closed

Notice that both orders are handled independently: one succeeded and ran .then(), the other failed and skipped straight to .catch(). In both cases, .finally() ran at the end.

Always reject with an Error object, like reject(new Error("...")), just as you would throw new Error(...). It gives you a message and a stack trace.


Turning Callbacks into Promises

A very common task is wrapping an old callback-based function in a promise. The classic example is a delay() (or sleep()) helper built on setTimeout():

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

console.log("Waiting...");

delay(1000).then(() => console.log("1 second later"));

Output:

Waiting...
1 second later

We'll use this delay() helper a lot to simulate slow operations like network requests.


Promise Chaining

Here's the feature that makes promises so much better than nested callbacks:

.then() always returns a NEW promise. Whatever you return from the callback becomes the value of that new promise.

So we can chain steps one after another:

Promise.resolve(2)
    .then(n => {
        console.log(n);
        return n * 3;
    })
    .then(n => {
        console.log(n);
        return n + 4;
    })
    .then(n => {
        console.log(n);
    });

Output:

2
6
10

(Promise.resolve(2) simply creates a promise that is already fulfilled with the value 2.)

If the callback returns another promise, the chain waits for it to settle before moving on. This lets us run async steps in sequence. Here is the callback-hell example from the previous chapter, rewritten with promises:

function step(name) {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log(name);
            resolve();
        }, 500);
    });
}

step("1. Log in")
    .then(() => step("2. Load profile"))
    .then(() => step("3. Load orders"))
    .then(() => step("4. Show dashboard"))
    .then(() => console.log("All done!"));

Output:

1. Log in
2. Load profile
3. Load orders
4. Show dashboard
All done!

Same result, but the code reads top to bottom instead of drifting to the right.

Passing Data Down the Chain

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function getUser(id) {
    return delay(300).then(() => ({ id, name: "Priya" }));
}

function getOrders(user) {
    return delay(300).then(() => ["Laptop", "Headphones"]);
}

getUser(7)
    .then(user => {
        console.log("User:", user.name);
        return getOrders(user);
    })
    .then(orders => {
        console.log("Orders:", orders.join(", "));
    });

Output:

User: Priya
Orders: Laptop, Headphones

Error Handling in Chains

If any step in a chain rejects or throws an error, JavaScript skips all the following .then() callbacks and jumps to the nearest .catch(), much like throw jumps to a catch block.

Promise.resolve(10)
    .then(n => {
        console.log("Step 1:", n);
        throw new Error("Something broke in step 2");
    })
    .then(n => {
        console.log("Step 3 (skipped)");
    })
    .catch(error => {
        console.log("Caught:", error.message);
        return "recovered";
    })
    .then(value => {
        console.log("Continuing with:", value);
    });

Output:

Step 1: 10
Caught: Something broke in step 2
Continuing with: recovered

Key points:

  • A throw inside .then() automatically turns into a rejected promise.

  • One .catch() at the end handles errors from every step above it.

  • .catch() also returns a promise. If it returns a normal value, the chain continues as fulfilled.

This solves the callback problem where try...catch couldn't catch errors from async code.

Unhandled Rejections

If a promise rejects and there is no .catch() anywhere in its chain, you get an unhandled promise rejection. Browsers log an error in the console; Node.js (version 15 and later) treats it like an uncaught exception and crashes the process by default. So always end your chains with a .catch().


Common Mistakes

1. Forgetting to return inside .then()

function delay(ms, value) {
    return new Promise(resolve => setTimeout(() => resolve(value), ms));
}

delay(100, 5)
    .then(n => {
        delay(100, n * 2);   // ❌ no return
    })
    .then(result => {
        console.log("Without return:", result);
    });

delay(100, 5)
    .then(n => {
        return delay(100, n * 2);   // ✅ returned
    })
    .then(result => {
        console.log("With return:", result);
    });

Output:

Without return: undefined
With return: 10

Without return, the next .then() doesn't wait and receives undefined. (Remember: an arrow function with curly braces needs an explicit return.)

2. Nesting promises instead of chaining

// ❌ This is just callback hell with promises
getUser(7).then(user => {
    getOrders(user).then(orders => {
        console.log(orders);
    });
});

// ✅ Return the promise and chain
getUser(7)
    .then(user => getOrders(user))
    .then(orders => console.log(orders));

3. Expecting a promise to give you a value directly

const result = Promise.resolve(42);

console.log(result);        // a Promise, not 42
result.then(v => console.log(v));

Output:

Promise { 42 }
42

You can only get the value inside .then() (or with await, in the next chapter).


Running Promises in Parallel

Sometimes several async operations don't depend on each other, like loading a user's profile, notifications, and settings. Running them one after another wastes time. JavaScript provides four static methods to work with many promises at once. Each takes an iterable (usually an array) of promises and returns a new promise.

Method

Fulfills when...

Rejects when...

Promise.all()

All fulfill. Value: array of all results, in input order

Any one rejects (fails fast)

Promise.allSettled()

All settle, whether success or failure. Value: array of status objects

Never (for an array of promises)

Promise.race()

The first to settle fulfills

The first to settle rejects

Promise.any()

The first to fulfill (ES2021)

All reject, with an AggregateError

Promise.all()

function load(name, ms) {
    return new Promise(resolve => setTimeout(() => resolve(name), ms));
}

const start = Date.now();

Promise.all([
    load("profile", 300),
    load("notifications", 100),
    load("settings", 200)
]).then(results => {
    console.log(results);
    console.log("Took less than 500ms:", Date.now() - start < 500);
});

Output:

[ 'profile', 'notifications', 'settings' ]
Took less than 500ms: true

Two things to notice:

  • The results are in the same order as the input array, not the order they finished.

  • All three ran at the same time, so the total time is about 300 ms (the slowest one), not 600 ms.

If any promise rejects, Promise.all() rejects immediately with that error:

Promise.all([
    Promise.resolve("A"),
    Promise.reject(new Error("B failed")),
    Promise.resolve("C")
])
    .then(results => console.log(results))
    .catch(error => console.log("Error:", error.message));

Output:

Error: B failed

Promise.allSettled()

Use it when you want every result, even if some fail:

Promise.allSettled([
    Promise.resolve("A"),
    Promise.reject(new Error("B failed")),
    Promise.resolve("C")
]).then(results => {
    results.forEach(r => {
        if (r.status === "fulfilled") {
            console.log("fulfilled:", r.value);
        } else {
            console.log("rejected:", r.reason.message);
        }
    });
});

Output:

fulfilled: A
rejected: B failed
fulfilled: C

Promise.race()

Settles as soon as the first promise settles. A common use is adding a timeout to a slow operation:

function load(name, ms) {
    return new Promise(resolve => setTimeout(() => resolve(name), ms));
}

function timeout(ms) {
    return new Promise((_, reject) =>
        setTimeout(() => reject(new Error("Timed out")), ms)
    );
}

Promise.race([load("fast data", 100), timeout(500)])
    .then(v => console.log("Got:", v))
    .catch(e => console.log(e.message));

Promise.race([load("slow data", 1000), timeout(500)])
    .then(v => console.log("Got:", v))
    .catch(e => console.log(e.message));

Output:

Got: fast data
Timed out

(The losing promises aren't cancelled. Their timers still run; their results are just ignored.)

Promise.any()

Fulfills with the first successful result and ignores failures, unless everything fails:

Promise.any([
    Promise.reject(new Error("Server 1 down")),
    Promise.resolve("Response from server 2"),
    Promise.resolve("Response from server 3")
]).then(v => console.log(v));

Promise.any([
    Promise.reject(new Error("Server 1 down")),
    Promise.reject(new Error("Server 2 down"))
]).catch(e => {
    console.log(e.name);
    console.log(e.errors.map(err => err.message));
});

Output:

Response from server 2
AggregateError
[ 'Server 1 down', 'Server 2 down' ]

Other Useful Helpers

  • Promise.resolve(value) creates an already-fulfilled promise.

  • Promise.reject(error) creates an already-rejected promise.

  • Promise.withResolvers() (ES2024) returns { promise, resolve, reject }, which is handy when you need to resolve a promise from outside its executor.

  • Promise.try(fn) (ES2025) calls fn and always gives back a promise, turning a synchronous throw into a rejection.

withResolvers() and try() are newer, but supported in current versions of all major browsers and Node.js.

const { promise, resolve } = Promise.withResolvers();

promise.then(v => console.log("Resolved with", v));

setTimeout(() => resolve("hello"), 100);

Output:

Resolved with hello

Callbacks vs Promises

Callbacks

Promises

Sequential steps nest deeper and deeper

Sequential steps form a flat chain

Errors handled separately at every level

One .catch() handles errors from the whole chain

Running things in parallel needs manual counting

Promise.all(), allSettled(), race(), any()

A buggy function might call your callback twice

A promise settles only once


Interview Tips and Practice

  • States: pending, fulfilled, rejected. "Settled" means fulfilled or rejected. A settled promise never changes.

  • Does the executor run synchronously? Yes. Only the .then()/.catch()/.finally() callbacks run later, as microtasks.

  • Promise.all vs Promise.allSettled: all fails fast on the first rejection; allSettled always waits for everything and reports each outcome.

  • Promise.race vs Promise.any: race takes the first to settle (success or failure); any takes the first success.

A classic interview task is writing your own version of Promise.all():

function promiseAll(promises) {
    return new Promise((resolve, reject) => {
        const results = [];
        let completed = 0;

        if (promises.length === 0) {
            resolve(results);
            return;
        }

        promises.forEach((p, index) => {
            Promise.resolve(p)
                .then(value => {
                    results[index] = value;   // keep input order
                    completed++;
                    if (completed === promises.length) {
                        resolve(results);
                    }
                })
                .catch(reject);              // fail fast
        });
    });
}

promiseAll([1, Promise.resolve(2), new Promise(r => setTimeout(() => r(3), 100))])
    .then(values => console.log(values));

Output:

[ 1, 2, 3 ]

Practice ideas:

  • Write a promisify(fn) helper that converts a callback-style function into one that returns a promise.

  • Write retry(fn, times) that calls an async function again if it fails, up to times attempts.

  • Write withTimeout(promise, ms) using Promise.race().

Conclusion

A promise is an object representing a future value:

pending → fulfilled (value)   handled by .then()
        → rejected  (error)   handled by .catch()
                              .finally() runs either way

The basic pattern:

doSomethingAsync()
    .then(result => doNextThing(result))
    .then(next => console.log(next))
    .catch(error => console.log(error.message))
    .finally(() => console.log("Done"));

Remember that .then() returns a new promise, so always return the next step to keep the chain connected. Use Promise.all() and friends to run independent tasks in parallel.

Promise chains are a huge improvement over callbacks, but there's an even cleaner way to write the same logic. In the next chapter, we'll learn async and await, which let you write asynchronous code that looks almost like normal synchronous code.