Introduction & Syntax
Promises · Study material
A Promise is an object representing a value that will be available later – the result of a network request, a file read or a timer. It starts pending and settles exactly once, either fulfilled with a value or rejected with a reason. Promises fixed the problems of callbacks – nesting, scattered error handling and untrustworthy callers – and they are the foundation of fetch, async/await and almost every modern API. Interviews test exactly how they behave: when the executor runs, what then returns, how errors propagate, why then callbacks run before timers, and the differences between all, allSettled, race and any. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.
States
A promise is pending until its producer calls resolve(value) or reject(reason). After that it is settled – fulfilled or rejected – and never changes again. Code that consumes it registers callbacks with then, catch and finally.
// A promise is pending, then settles once: fulfilled (with a value) or rejected (with a reason)
const PENDING = Symbol("pending");
const stateOf = (p) =>
Promise.race([p, PENDING]).then(
(v) => (v === PENDING ? "pending" : `fulfilled (${v})`),
(e) => `rejected (${e.message})`,
);
const ok = new Promise((resolve) => resolve("data"));
const failed = new Promise((_, reject) => reject(new Error("network down")));
const waiting = new Promise(() => {}); // never settles
Promise.all([stateOf(ok), stateOf(failed), stateOf(waiting)]).then((s) => console.log(s.join(" | ")));
fulfilled (data) | rejected (network down) | pending
The executor runs synchronously; promises settle once
new Promise((resolve, reject) => { … }) runs the executor function immediately, during the constructor call. Only the first call to resolve or reject counts; later calls are ignored. Callbacks passed to then never run synchronously – even for an already-settled promise they are queued as microtasks.
console.log("1. before");
const p = new Promise((resolve, reject) => {
console.log("2. the executor runs immediately");
resolve("first");
resolve("second"); // ignored: a promise settles only once
reject(new Error("too late")); // ignored too
});
p.then((v) => console.log("4. then:", v)); // then callbacks always run later (as microtasks)
console.log("3. after");
1. before 2. the executor runs immediately 3. after 4. then: first
Chaining
then always returns a new promise, resolved with whatever the callback returns. Return a plain value and it is passed to the next then; return a promise and the chain waits for it (promises are flattened); return nothing and the next step receives undefined – the most common promise bug is a forgotten return.
Promise.resolve(2)
.then((n) => n * 10) // return a value → passed on
.then((n) => new Promise((r) => setTimeout(() => r(n + 5), 10))) // return a promise → the chain waits
.then((n) => { console.log("result:", n); }) // returns nothing (undefined)
.then((v) => console.log("next gets:", v));
result: 25 next gets: undefined
Error handling
A thrown error or a rejected promise anywhere in the chain skips the following then callbacks until a catch (or a then with a second, rejection callback). catch handles it and returns a new promise – fulfilled with whatever catch returns, so the chain can recover. finally runs on both outcomes, receives no value and passes the original result through (unless it throws).
Promise.resolve("start")
.then(() => { throw new Error("step 2 failed"); })
.then(() => console.log("skipped")) // skipped: the chain is now rejected
.catch((e) => {
console.log("caught:", e.message);
return "recovered"; // a value from catch fulfils the chain again
})
.then((v) => console.log("continues with:", v))
.finally(() => console.log("finally: always runs"));
caught: step 2 failed continues with: recovered finally: always runs
Microtasks run before timers
Promise callbacks go into the microtask queue, which is emptied completely after the current synchronous code and before the next timer or I/O callback (a task). So a then callback always runs before a setTimeout(…, 0) callback scheduled at the same time. The Event Loop topic covers the full order.
setTimeout(() => console.log("3. timeout (task)"), 0);
Promise.resolve().then(() => console.log("2. then (microtask)"));
console.log("1. sync");
// All synchronous code first, then every microtask, then the next timer
1. sync 2. then (microtask) 3. timeout (task)
Combining promises
| Method | Fulfils when | Rejects when |
|---|---|---|
Promise.all | all fulfil (values in input order) | any rejects – immediately (fail-fast) |
Promise.allSettled | all settle – with { status, value | reason } objects | never |
Promise.race | the first to settle fulfils | the first to settle rejects |
Promise.any | the first to fulfil | all reject – with an AggregateError |
const delay = (ms, v, fail = false) =>
new Promise((res, rej) => setTimeout(() => (fail ? rej(new Error(v)) : res(v)), ms));
Promise.all([delay(20, "a"), delay(10, "b")]).then((v) => console.log("all:", v)); // all must succeed
Promise.allSettled([delay(5, "ok"), delay(5, "bad", true)])
.then((r) => console.log("allSettled:", r.map((x) => x.status))); // never rejects
Promise.race([delay(15, "slow"), delay(5, "fast")]).then((v) => console.log("race:", v)); // first to settle
Promise.any([delay(5, "e1", true), delay(12, "winner")]).then((v) => console.log("any:", v)); // first to succeed
allSettled: [ 'fulfilled', 'rejected' ] race: fast any: winner all: [ 'a', 'b' ]
Promise.resolve, Promise.reject and thenables
Promise.resolve(x) returns x itself if it is already a promise, adopts any thenable (an object with a then method) and otherwise wraps the value. Promise.reject(reason) creates a rejected promise. A rejection that is never handled triggers an unhandled rejection – in Node.js that terminates the process.
const p = Promise.resolve(1);
console.log(Promise.resolve(p) === p); // a real promise is returned as it is
// Any object with a then method ("thenable") is adopted by promises
const thenable = { then(resolve) { resolve(42); } };
Promise.resolve(thenable).then((v) => console.log("thenable gave", v));
Promise.reject(new Error("nope")).catch((e) => console.log("rejected with", e.message));
// (adopting a thenable takes one extra microtask, so the rejection above is reported first)
true rejected with nope thenable gave 42
Common mistakes
- Forgetting return inside then – the next step gets undefined and does not wait.
- Nesting then calls instead of returning the inner promise – timing and errors break.
- No catch at the end of a chain – unhandled rejections (Node.js exits).
- Expecting forEach to wait for promises – use Promise.all with map.
- Using Promise.all when some calls may fail – use allSettled.
- Wrapping existing promises in new Promise – errors are easily lost; return the chain.
- Thinking then runs synchronously – callbacks always run later, as microtasks.
Key points to remember
- Pending → fulfilled or rejected, exactly once.
- The executor runs synchronously; then/catch/finally callbacks run asynchronously.
- then returns a new promise; returned promises are flattened.
- Errors skip to the next catch; catch can recover the chain.
- finally runs on both outcomes and passes the result through.
- Microtasks (promise callbacks) run before the next timer.
- all (fail-fast), allSettled (never rejects), race (first settled), any (first fulfilled).
Frequently asked questions
Promises or async/await?
async/await is syntax built on promises: an async function returns a promise and await waits for one. Use whichever reads best – most code uses await, while combinators like Promise.all are still promise methods.
Can a promise be cancelled?
Not directly. APIs such as fetch use an AbortController to stop the underlying work, which then rejects the promise.
Why does Node.js crash on an unhandled rejection?
Since Node.js 15 an unhandled rejection is treated like an uncaught exception, because silently ignoring failures hides bugs. Always end chains with catch (or try…catch around await).
Where can I learn more?
Read Promises, async and await and The Event Loop in the JavaScript tutorial, then practise with the exercises below.