JavaScript Promises Explained: States, then, catch, finally and Chaining
A promise is an object that represents a value you will get later: the result of an API call, a file read or a page navigation. Promises replaced nested callbacks with flat, chainable code, and they are the foundation of async/await and of every Playwright command, since page.click(), page.goto() and expect() all return promises. In this lesson you will learn how promises work, how to create and consume them, how errors flow through a chain, and the mistakes that cause unhandled rejections and flaky tests.
📖 What You’ll Learn: what a promise is, the three states, creating promises with new Promise, resolve and reject, consuming them with then, catch and finally, chaining and returning values or promises, error propagation through a chain, Promise.resolve and Promise.reject, promisifying callback APIs, common mistakes (forgetting return, nesting, missing catch), unhandled rejections, and promises in tests.
🤝 What Is a Promise?
Definition: a promise is an object representing the eventual result of an asynchronous operation. It is a placeholder: you get it immediately, and it later becomes either a value or an error.
A promise is always in one of three states:
| State | Meaning |
|---|---|
| pending | The operation is still running |
| fulfilled | It finished successfully and has a value |
| rejected | It failed and has a reason (usually an Error) |
Once a promise is fulfilled or rejected it is settled, and it never changes state again.
📄 states.js
const util = require("node:util");
const pending = new Promise(() => {});
const fulfilled = Promise.resolve(42);
const rejected = Promise.reject(new Error("failed"));
rejected.catch(() => {}); // handle it so Node.js does not report it
console.log(util.inspect(pending));
console.log(util.inspect(fulfilled));
console.log(util.inspect(rejected).split("\n").slice(0, 2).map((s) => s.trim()).join(" "), "}");
⌨️ Terminal
node states.js
🖥️ Output
Promise { <pending> }
Promise { 42 }
Promise { <rejected> Error: failed }
🏗️ Creating a Promise
The Promise constructor takes an executor function that receives two functions: call resolve(value) on success and reject(error) on failure. The executor runs immediately.
📄 create.js
function fetchOrder(id) {
return new Promise((resolve, reject) => {
console.log(`executor runs immediately for order ${id}`);
setTimeout(() => {
if (id <= 0) reject(new Error(`Order ${id} not found`));
else resolve({ id, total: 1299 });
}, 20);
});
}
const p = fetchOrder(451);
console.log("got a promise right away:", p instanceof Promise);
p.then((order) => console.log("fulfilled with", order));
fetchOrder(-1).catch((err) => console.log("rejected with", err.message));
⌨️ Terminal
node create.js
🖥️ Output
executor runs immediately for order 451
got a promise right away: true
executor runs immediately for order -1
fulfilled with { id: 451, total: 1299 }
rejected with Order -1 not found
- Only the first call to
resolveorrejectcounts; later calls are ignored. - Always reject with an
Errorobject so stack traces andinstanceofwork. - If the executor throws, the promise is rejected automatically.
📥 Consuming: then, catch and finally
| Method | Runs when | Typical use |
|---|---|---|
.then(onFulfilled) | The promise is fulfilled | Use the value |
.catch(onRejected) | The promise is rejected | Handle or report the error |
.finally(onSettled) | Either way | Cleanup: hide a spinner, close a connection |
📄 then-catch.js
const delay = (ms) => new Promise((r) => setTimeout(r, ms));
function login(user) {
return delay(10).then(() => {
if (!user) throw new Error("username is required");
return { user, token: "t-123" };
});
}
login("asha")
.then((session) => console.log("logged in:", session.token))
.catch((err) => console.log("error:", err.message))
.finally(() => console.log("cleanup after first login"));
login("")
.then((session) => console.log("logged in:", session.token))
.catch((err) => console.log("error:", err.message))
.finally(() => console.log("cleanup after second login"));
⌨️ Terminal
node then-catch.js
🖥️ Output
logged in: t-123
cleanup after first login
error: username is required
cleanup after second login
.then callbacks always run asynchronously (as microtasks), even when the promise is already settled. See the Event Loop lesson for the exact order.
⛓️ Chaining Promises
Every call to .then returns a new promise, which is what makes chains possible. What the callback returns decides what the next step receives:
- Return a value: the next
.thenreceives that value. - Return a promise: the chain waits for it and passes on its result.
- Return nothing: the next step receives
undefined. - Throw: the chain skips to the next
.catch.
📄 chain.js
const delay = (ms, value) => new Promise((r) => setTimeout(() => r(value), ms));
const api = {
login: (user) => delay(10, { token: `token-for-${user}` }),
getCart: (token) => delay(10, { token, items: [{ price: 499 }, { price: 1299 }] }),
checkout: (cart) => delay(10, { orderId: 451, total: cart.items.reduce((s, i) => s + i.price, 0) }),
};
api.login("asha")
.then((session) => api.getCart(session.token)) // return a promise: the chain waits
.then((cart) => api.checkout(cart))
.then((order) => `Order ${order.orderId} total ₹${order.total}`) // return a value
.then((message) => console.log(message))
.catch((err) => console.log("checkout flow failed:", err.message));
⌨️ Terminal
node chain.js
🖥️ Output
Order 451 total ₹1798
Compare this flat chain with the nested callback version in the Callbacks and Timers lesson: one level of indentation and one .catch for the whole flow.
🚨 Error Propagation
An error (a rejection or a thrown exception) skips every following .then until it reaches a .catch. After a .catch handles it, the chain continues normally with the value the .catch returned:
📄 propagation.js
Promise.resolve(1)
.then((n) => { console.log("step 1:", n); return n + 1; })
.then((n) => { throw new Error(`step 2 failed with ${n}`); })
.then(() => console.log("step 3: skipped"))
.catch((err) => { console.log("caught:", err.message); return "fallback"; })
.then((value) => console.log("chain continues with:", value));
⌨️ Terminal
node propagation.js
🖥️ Output
step 1: 1
caught: step 2 failed with 2
chain continues with: fallback
💡 Tip: Put one .catch at the end of a chain to handle failures from any step. Add a .catch in the middle only if you can genuinely recover, such as using cached data when a request fails.
🧰 Promise.resolve, Promise.reject and promisify
Promise.resolve(value) and Promise.reject(error) create already-settled promises, which is useful for tests, defaults and functions that must always return a promise:
📄 resolve-reject.js
function getConfig(useCache) {
if (useCache) return Promise.resolve({ env: "qa", cached: true }); // still a promise
return new Promise((r) => setTimeout(() => r({ env: "qa", cached: false }), 10));
}
getConfig(true).then((c) => console.log("cache:", c));
getConfig(false).then((c) => console.log("fresh:", c));
Promise.reject(new Error("not allowed")).catch((e) => console.log("rejected:", e.message));
⌨️ Terminal
node resolve-reject.js
🖥️ Output
cache: { env: 'qa', cached: true }
rejected: not allowed
fresh: { env: 'qa', cached: false }
Old callback-based APIs can be wrapped into promises with util.promisify, or by hand. Most Node.js modules also have a promise version already, such as node:fs/promises:
📄 promisify.js
const fs = require("node:fs");
const util = require("node:util");
const fsp = require("node:fs/promises");
fs.writeFileSync("note.txt", "hello promises");
const readFileAsync = util.promisify(fs.readFile);
readFileAsync("note.txt", "utf8").then((text) => console.log("promisify:", text));
fsp.readFile("note.txt", "utf8").then((text) => console.log("fs/promises:", text));
⌨️ Terminal
node promisify.js
🖥️ Output
promisify: hello promises
fs/promises: hello promises
⚠️ Common Promise Mistakes
1. Forgetting to return inside then
📄 no-return.js
const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
delay(10, 1)
.then((n) => { delay(10, n + 1); }) // promise created but not returned
.then((n) => console.log("without return:", n));
delay(10, 1)
.then((n) => delay(10, n + 1)) // returned: the chain waits for it
.then((n) => console.log("with return:", n));
⌨️ Terminal
node no-return.js
🖥️ Output
without return: undefined
with return: 2
Without return, the next step does not wait and receives undefined, and any error in the forgotten promise is lost.
2. Nesting then inside then
Writing a().then((x) => { b(x).then((y) => { c(y).then(...) }) }) rebuilds callback hell. Return the inner promise and chain at the top level instead.
3. No catch: unhandled rejections
A rejected promise that nobody handles is an unhandled rejection. Since Node.js 15, it crashes the process:
📄 unhandled.js
function deleteUser(id) {
return Promise.reject(new Error(`User ${id} is protected and cannot be deleted`));
}
deleteUser(1); // no .catch and no await
console.log("this line still runs first");
⌨️ Terminal
node unhandled.js
🖥️ Output
this line still runs first
/home/you/js-course/unhandled.js:2
return Promise.reject(new Error(`User ${id} is protected and cannot be deleted`));
^
Error: User 1 is protected and cannot be deleted
at deleteUser (/home/you/js-course/unhandled.js:2:25)
at Object.<anonymous> (/home/you/js-course/unhandled.js:5:1)
Node.js v26.13.0
⚠️ Watch out: Every promise chain needs a .catch at the end, or must be awaited inside a try. In test code, an unhandled rejection can crash a worker and hide which test caused it.
🧪 Tester Scenario: Promise-Based Test Steps
Each step of a test returns a promise; chaining runs them in order, a failure in any step skips the rest and is reported once, and finally always cleans up the test data:
📄 test-steps.js
const delay = (ms) => new Promise((r) => setTimeout(r, ms));
const log = [];
const step = (name, fn) => () => delay(5).then(() => {
log.push(name);
return fn();
});
const createUser = step("create user", () => ({ id: 77 }));
const addToCart = step("add to cart", () => ({ items: 1 }));
const payWithCard = step("pay with card", () => { throw new Error("Payment API returned 502"); });
const verifyOrder = step("verify order", () => true);
createUser()
.then(addToCart)
.then(payWithCard)
.then(verifyOrder)
.then(() => console.log("TEST PASSED"))
.catch((err) => console.log(`TEST FAILED at step ${log.length}: ${err.message}`))
.finally(() => console.log("steps run:", log.join(" -> "), "| cleanup: delete user 77"));
⌨️ Terminal
node test-steps.js
🖥️ Output
TEST FAILED at step 3: Payment API returned 502
steps run: create user -> add to cart -> pay with card | cleanup: delete user 77
In practice you will write this with async/await (lesson 50), which reads like synchronous code, but it is built on exactly these promise rules.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Create a function wait(ms) that returns a promise resolving after ms milliseconds, and use it to print "ready" after 20 ms.
Show answer
📄 practice1.js
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
wait(20).then(() => console.log("ready"));🖥️ Output
readyQ2. Write checkAge(age) that returns a promise resolving with "allowed" for 18+ and rejecting with an Error otherwise. Test with 21 and 15.
Show answer
📄 practice2.js
const checkAge = (age) => new Promise((resolve, reject) =>
age >= 18 ? resolve("allowed") : reject(new Error(`age ${age} is under 18`)));
checkAge(21).then(console.log).catch((e) => console.log(e.message));
checkAge(15).then(console.log).catch((e) => console.log(e.message));🖥️ Output
allowed
age 15 is under 18Q3. Chain three steps: start with 2, double it, add 10, then print the result.
Show answer
📄 practice3.js
Promise.resolve(2)
.then((n) => n * 2)
.then((n) => n + 10)
.then((n) => console.log(n));🖥️ Output
14Q4. Predict the output, then run it.
Promise.resolve("A")
.then((v) => { throw new Error(v + "B"); })
.then(() => console.log("C"))
.catch((e) => e.message + "D")
.then((v) => console.log(v))
.finally(() => console.log("E"));Show answer
📄 practice4.js
Promise.resolve("A")
.then((v) => { throw new Error(v + "B"); })
.then(() => console.log("C"))
.catch((e) => e.message + "D")
.then((v) => console.log(v))
.finally(() => console.log("E"));🖥️ Output
ABD
EThe thrown error skips “C”, the catch returns “ABD” which the next then prints, and finally always runs.
Q5. Convert this callback function to return a promise using util.promisify.
function getStatus(url, cb) {
setTimeout(() => cb(null, url.includes("health") ? 200 : 404), 5);
}Show answer
📄 practice5.js
const util = require("node:util");
function getStatus(url, cb) {
setTimeout(() => cb(null, url.includes("health") ? 200 : 404), 5);
}
const getStatusAsync = util.promisify(getStatus);
getStatusAsync("/health").then((s) => console.log("status", s));🖥️ Output
status 200Q6. This chain prints undefined. Fix it so it prints "token-123".
const login = () => new Promise((r) => setTimeout(() => r("token-123"), 10));
Promise.resolve()
.then(() => { login(); })
.then((token) => console.log(token));Show answer
📄 practice6.js
const login = () => new Promise((r) => setTimeout(() => r("token-123"), 10));
Promise.resolve()
.then(() => login())
.then((token) => console.log(token));🖥️ Output
token-123Return the promise from the callback (the arrow function without braces returns it implicitly).
🧠 MCQ Quiz: Promises
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What are the three states of a promise?Answer: pending, fulfilled, rejected. Fulfilled and rejected are both “settled”.
- When does the executor function of new Promise run?Answer: Immediately, synchronously. Only the resolve/reject reactions are asynchronous.
- What does .then() return?Answer: A new promise. That is what makes chaining possible.
- If a then callback returns a promise, what does the next then receive?Answer: The resolved value of that promise. The chain waits for returned promises.
- What happens when a then callback throws?Answer: The chain skips to the next catch. Throwing is equivalent to returning a rejected promise.
- When does finally run?Answer: After the promise settles, whether fulfilled or rejected. Use it for cleanup.
- Since Node.js 15, what does an unhandled promise rejection do by default?Answer: Crashes the process. Always add catch or await inside try.
- What is wrong with
.then(() => { fetchData(); })?Answer: The promise is not returned, so the chain does not wait for it. Return it, or use an expression body. - What does
Promise.resolve(5)create?Answer: A promise already fulfilled with 5. Promise.reject creates an already rejected one. - Which converts an error-first callback function into a promise-returning one?Answer: util.promisify. Many modules also offer promise APIs directly, such as fs/promises.
💼 Interview Questions and Answers
Q1. What is a promise and why was it introduced?
A promise is an object representing the eventual result of an asynchronous operation, in one of three states: pending, fulfilled or rejected. Promises replaced nested callbacks with composable chains, give one consistent way to handle errors (rejections propagate to .catch), and can be combined (Promise.all etc.). They are the basis of async/await.
Q2. What is the difference between returning and not returning inside then?
Returning a value passes it to the next .then; returning a promise makes the chain wait and pass on its result; throwing rejects the chain. Not returning means the next step runs immediately with undefined, and any promise created inside is “floating”: its errors are not caught by the chain’s .catch.
Q3. Predict the output.
📄 predict.js
const p = new Promise((resolve) => {
console.log(1);
resolve(2);
console.log(3);
});
p.then((v) => console.log(v));
console.log(4);
⌨️ Terminal
node predict.js
🖥️ Output
1
3
4
2
The executor runs synchronously, so 1 and 3 print immediately (resolve does not stop the executor). Then the synchronous 4, and finally the then callback prints 2 as a microtask.
Q4. What is an unhandled promise rejection and how do you prevent it?
It is a rejected promise with no rejection handler attached by the time the microtask queue is processed. Node.js emits unhandledRejection and, by default since v15, terminates the process. Prevent it by ending every chain with .catch, awaiting promises inside try...catch, not leaving “floating” promises (lint rule no-floating-promises), and logging in a global process.on("unhandledRejection") handler as a last resort.
❓ Frequently Asked Questions
🤔 Can a promise be resolved twice?
No. The first resolve or reject settles it; later calls are ignored.
🤔 Are promises asynchronous?
The executor runs synchronously, but then, catch and finally callbacks always run asynchronously as microtasks.
🤔 Should I use then/catch or async/await?
Use async/await for most code; it is easier to read and debug. then chains are still useful for short transformations and for running code without making the surrounding function async.
🤔 Can I cancel a promise?
Not directly. Cancel the underlying operation with an AbortController signal where the API supports it, such as fetch and Node.js timers.
🏁 Summary
- A promise represents a future value and is pending, fulfilled or rejected; once settled it never changes.
- Create promises with
new Promise((resolve, reject) => ...),Promise.resolveandPromise.reject. - Consume them with
then,catchandfinally; eachthenreturns a new promise, which enables chaining. - Errors skip to the next
catch; always return promises insidethenand end chains withcatch. - Unhandled rejections crash Node.js; promisify callback APIs with
util.promisifyor use built-in promise modules.
Next, continue with Lesson 49: Promise.all, allSettled, race, any.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in