Promises
A promise is an object that represents the eventual result of an asynchronous operation: a value that isn't available yet but will be (or an error explaining why not). Instead of passing a callback into a function, the function returns a promise, and you attach handlers to it with then, catch and finally. Promises can be chained, so a sequence of async steps reads top to bottom, and one catch handles errors from every step. They are also the foundation that async and await are built on.
In One Minute
- A promise is pending, then settles once as fulfilled (with a value) or rejected (with a reason, usually an
Error). promise.then(onFulfilled)runs when it fulfills;.catch(onRejected)when it rejects;.finally(fn)either way.thenreturns a new promise, so calls chain; returning a value (or a promise) from a handler passes it down the chain.- Create one with
new Promise((resolve, reject) => { ... }), orPromise.resolve(v)/Promise.reject(err). Promise.withResolvers()(ES2024) andPromise.try()(ES2025) cover two common creation patterns.
Promise States
| State | Meaning | Can change? |
|---|---|---|
| Pending | The operation hasn't finished | Yes, to fulfilled or rejected |
| Fulfilled | Finished successfully, with a value | No |
| Rejected | Failed, with a reason (an error) | No |
"Fulfilled" and "rejected" together are called settled. A promise settles at most once: after that, its value or reason never changes, and handlers attached later still receive it.
const fulfilled = Promise.resolve(120);
const rejected = Promise.reject(new Error("Card declined"));
fulfilled.then((value) => console.log("fulfilled with", value));
rejected.catch((err) => console.log("rejected with", err.message));
const later = new Promise((resolve) => setTimeout(() => resolve("ready"), 20));
console.log(later instanceof Promise);
later.then((v) => console.log("later:", v));true
fulfilled with 120
rejected with Card declined
later: readyNotice that even for promises that are already settled, handlers run asynchronously, after the current code (as microtasks; see the event loop lesson).
then, catch and finally
| Method | Called when | Receives |
|---|---|---|
.then(onFulfilled, onRejected?) | The promise fulfills (or rejects, if the second handler is given) | The value (or reason) |
.catch(onRejected) | The promise rejects; same as .then(undefined, onRejected) | The reason |
.finally(onFinally) | The promise settles either way | Nothing; passes the original result through |
function chargeCard(amount) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (amount > 500) reject(new Error(`Limit exceeded: $${amount}`));
else resolve({ amount, confirmation: `C-${amount}` });
}, 10);
});
}
for (const amount of [120, 900]) {
chargeCard(amount)
.then((result) => console.log("Charged", result.confirmation))
.catch((err) => console.log("Failed:", err.message))
.finally(() => console.log(`Done with $${amount}`));
}Charged C-120
Done with $120
Failed: Limit exceeded: $900
Done with $900finally is for cleanup that must happen either way (hiding a spinner, re-enabling a button). It doesn't receive the value, and it doesn't change the result unless it throws.
Chaining
then always returns a new promise, which settles with whatever the handler returns. That is what makes chains work:
| The handler... | The new promise... |
|---|---|
| Returns a value | Fulfills with that value |
| Returns a promise | Follows it: settles when it settles, the same way |
| Throws an error | Rejects with that error |
| Returns nothing | Fulfills with undefined |
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
wait(10, 2)
.then((studentId) => {
console.log("1. got student id", studentId);
return wait(10, { id: studentId, name: "Srihitha" });
})
.then((student) => {
console.log("2. got student", student.name);
return [200, 150];
})
.then((payments) => {
const paid = payments.reduce((a, b) => a + b, 0);
console.log("3. paid", paid);
return 450 - paid;
})
.then((balance) => console.log("4. balance", balance));1. got student id 2
2. got student Srihitha
3. paid 350
4. balance 100The first handler returns a promise; the chain waits for it before calling the next then with its value. The second returns a plain array, which is passed straight on. Compare this flat chain with the nested callbacks in the previous lesson.
Error Propagation
A rejection skips every then until it reaches a catch, like a thrown exception skipping code until a catch block. After a catch handles it, the chain continues normally:
Promise.resolve(450)
.then((fee) => {
console.log("step 1");
throw new Error("Payment service is down");
})
.then(() => console.log("step 2: skipped"))
.then(() => console.log("step 3: skipped"))
.catch((err) => {
console.log("caught:", err.message);
return "used cached data";
})
.then((value) => console.log("continues with:", value));step 1
caught: Payment service is down
continues with: used cached dataOne catch at the end handles errors from every step above it.
Creating Promises
The Promise Constructor
new Promise(executor) takes a function, the executor, that receives resolve and reject functions. Call one of them when the operation finishes:
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function loadImageSize(src) {
return new Promise((resolve, reject) => {
if (!src.endsWith(".png")) {
reject(new TypeError(`Unsupported image: ${src}`));
return;
}
setTimeout(() => resolve({ src, width: 120, height: 80 }), 10);
});
}
await delay(10);
console.log("waited");
loadImageSize("logo.png").then((s) => console.log(s.width, s.height));
loadImageSize("logo.gif").catch((err) => console.log(err.name, err.message));waited
TypeError Unsupported image: logo.gif
120 80The executor runs immediately and synchronously when the promise is created. If the executor throws, the promise rejects. Calling resolve or reject again after the first time does nothing.
Converting Callback APIs
The constructor's main job today is wrapping callback-based APIs so they return promises:
function getStudentCallback(id, cb) {
setTimeout(() => (id === 1 ? cb(null, { name: "Navika" }) : cb(new Error(`No student ${id}`))), 5);
}
function getStudent(id) {
return new Promise((resolve, reject) => {
getStudentCallback(id, (err, student) => (err ? reject(err) : resolve(student)));
});
}
getStudent(1).then((s) => console.log(s.name));
getStudent(9).catch((err) => console.log(err.message));Navika
No student 9In Node.js, util.promisify(fn) does this conversion automatically for error-first callback functions.
Promise.resolve and Promise.reject
Promise.resolve(value) creates an already-fulfilled promise (or returns value unchanged if it's already a promise); Promise.reject(reason) creates an already-rejected one. They're useful for returning a promise consistently from a function that sometimes has the answer immediately, such as a cache hit.
Promise.withResolvers (ES2024)
Sometimes resolve and reject must be called from outside the executor, for example from an event handler set up elsewhere. Promise.withResolvers() returns the promise and both functions together:
function waitForEvent(target, type) {
const { promise, resolve } = Promise.withResolvers();
target.addEventListener(type, resolve, { once: true });
return promise;
}
const emitter = new EventTarget();
setTimeout(() => emitter.dispatchEvent(new Event("paid")), 10);
const event = await waitForEvent(emitter, "paid");
console.log("received", event.type);received paidBefore ES2024, this needed the awkward pattern of declaring let resolve, reject; and assigning them inside the executor.
Promise.try (ES2025)
When a function might be synchronous or asynchronous, and might throw synchronously, Promise.try(fn) calls it and always returns a promise, turning synchronous throws into rejections:
function readSetting(key) {
if (typeof key !== "string") throw new TypeError("key must be a string");
return key === "currency" ? "USD" : Promise.resolve(25);
}
Promise.try(() => readSetting("currency")).then((v) => console.log("currency:", v));
Promise.try(() => readSetting("pageSize")).then((v) => console.log("pageSize:", v));
Promise.try(() => readSetting(42)).catch((err) => console.log("caught:", err.message));currency: USD
caught: key must be a string
pageSize: 25Without Promise.try, the synchronous TypeError would be thrown out of readSetting(42) immediately instead of going to catch. (The order of the last two lines follows from the extra microtask step needed to unwrap the returned promise.)
In Practice
The Fee Tracker's "record payment" flow, as a promise chain: validate, save, update the balance, and always re-enable the button:
const api = {
save: (p) => new Promise((resolve, reject) =>
setTimeout(() => (p.amount > 450 ? reject(new Error("Amount exceeds the balance")) : resolve({ ...p, id: 7 })), 10)),
balance: (name) => Promise.resolve(name === "Navika" ? 250 : 450),
};
function recordPayment(payment) {
console.log(`Button disabled for ${payment.name}`);
return Promise.try(() => {
if (!(payment.amount > 0)) throw new RangeError("Enter a positive amount");
return api.save(payment);
})
.then((saved) => api.balance(saved.name).then((balance) => ({ saved, balance })))
.then(({ saved, balance }) => console.log(`Saved #${saved.id}; ${saved.name} now owes $${balance}`))
.catch((err) => console.log(`Could not save: ${err.message}`))
.finally(() => console.log("Button enabled"));
}
await recordPayment({ name: "Navika", amount: 200 });
await recordPayment({ name: "Advitha", amount: -5 });Button disabled for Navika
Saved #7; Navika now owes $250
Button enabled
Button disabled for Advitha
Could not save: Enter a positive amount
Button enabledCommon Mistakes
Forgetting to return in a then handler. The chain doesn't wait, and the next step gets undefined.
Nesting then inside then. That recreates callback hell. Return the inner promise and chain instead.
No catch at the end of a chain. Rejections become "unhandled rejections", which Node.js treats as crashes. Always end a chain with catch, or await it inside try.
Wrapping a promise in new Promise unnecessarily. new Promise((res) => fetch(u).then(res)) loses errors. Just return fetch(u).
Under the Hood
A promise is an object with internal slots: its state, its result, and two lists of reactions (fulfill and reject handlers registered while pending). Calling then creates a new "derived" promise and registers a reaction pairing your handler with it. When the original settles, it doesn't call handlers directly; it queues one PromiseReactionJob per reaction on the microtask queue. Each job runs your handler and settles the derived promise with the result. That's why handlers always run asynchronously, why chains propagate values and errors, and why many promises settling at once all run before the next timer. "Resolving" a promise with another promise or thenable (any object with a then method) queues an extra job that calls its then, adopting its eventual state, which costs one additional microtask tick, as the Promise.try example's ordering shows.
Interview Corner
What are the states of a promise?
Pending, then settled as either fulfilled (with a value) or rejected (with a reason). Settling happens at most once and is permanent; handlers attached after settlement still run, asynchronously.
What does then return?
A new promise, resolved with the handler's return value (or following it if it's a promise or thenable), or rejected if the handler throws. If no handler applies (for example, a rejection reaches then with only a fulfillment handler), the new promise settles the same way as the original, which is how errors propagate to a later catch.
What does this print?
Show solution
Promise.resolve(1)
.then((x) => x + 1)
.then((x) => { throw new Error(String(x * 10)); })
.then(() => console.log("skipped"))
.catch((e) => Number(e.message) + 1)
.finally(() => console.log("finally"))
.then((x) => console.log("value:", x));finally
value: 211 becomes 2, then an error with message "20" skips to catch, which returns 21. finally passes the value through unchanged.
Practice
Challenge: Write timeout(promise, ms) that returns a promise rejecting with Error("Timed out") if promise doesn't settle within ms, otherwise settling like promise. Test it with a fast and a slow promise.
Show solution
function timeout(promise, ms) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error("Timed out")), ms);
promise.then(resolve, reject).finally(() => clearTimeout(timer));
});
}
const wait = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
console.log(await timeout(wait(10, "fast"), 50));
await timeout(wait(100, "slow"), 20).catch((e) => console.log(e.message));fast
Timed outKey Takeaways
| Task | Code |
|---|---|
| Handle success | p.then((v) => ...) |
| Handle failure | p.catch((err) => ...) |
| Cleanup | p.finally(() => ...) |
| Wrap a callback API | new Promise((resolve, reject) => api(..., (e, r) => e ? reject(e) : resolve(r))) |
| Resolve from outside | const { promise, resolve, reject } = Promise.withResolvers() |
| Sync or async function | Promise.try(() => fn()) |
Was this tutorial helpful?