Promises — JavaScript interview guide
Promises
A promise is an object that represents a value that will be ready later. It is pending, then either fulfilled or rejected, and you react with .then, .catch and .finally.
See it run
Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.
Promise chain vs setTimeout ordering
▶console.log(1);23setTimeout(() => console.log(2), 0);45Promise.resolve()6.then(() => console.log(3))7.then(() => console.log(4));89console.log(5);
empty
empty
Waits until the Call Stack is empty. Microtasks always go first.
empty
empty
What happens:Synchronous: prints 1.
Tip: click the box and use ← → keys to step, space to play.
Explained simply
Creating and using a promise
resolve and reject can be called only once; later calls are ignored.
const getData = () =>
new Promise((resolve, reject) => {
setTimeout(() => {
Math.random() > 0.5 ? resolve("data") : reject(new Error("failed"));
}, 500);
});
getData()
.then((d) => d.toUpperCase()) // return value → next .then
.catch((e) => console.error(e)) // catches any error above
.finally(() => console.log("done"));Combinators
Promise.all: waits for all, rejects on the first error.
Promise.allSettled: waits for all, never rejects, gives status of each.
Promise.race: settles with the first one to settle.
Promise.any: resolves with the first success, rejects only if all fail.
Remember this
- Always return inside .then to keep the chain going.
- One .catch at the end handles errors from every step above it.
- .then callbacks run as microtasks, even for already-resolved promises.
Interview questions
Difference between Promise.all and Promise.allSettled?
all rejects as soon as one promise rejects; allSettled waits for every promise and returns { status, value | reason } for each.
What happens if you throw inside .then?
The promise returned by that .then rejects, and the next .catch in the chain receives the error.
Practice
- Implement Promise.all from scratch.
- Write a timeout(promise, ms) helper using Promise.race.
Keep learning
More in Async JavaScript