Concept
Promises
Objects that represent a value that will be available later, with then/catch chaining.
Promises explained
A promise is an object that stands for a value that is not ready yet. It starts pending and settles once, either fulfilled with a value or rejected with an error. You attach reactions with .then and .catch, and because every .then returns a new promise, steps chain in order instead of nesting callbacks.
How promises chain
fetch("/api/user")
.then((res) => res.json()) // return a value or another promise
.then((user) => fetch(`/api/orders/${user.id}`))
.then((res) => res.json())
.catch((err) => console.error(err)) // one place for any error above
.finally(() => hideSpinner());
Whatever a .then callback returns becomes the value of the next promise. If it returns a promise, the chain waits for it. If anything throws, control jumps to the nearest .catch.
Running promises together
Promise.all: waits for all of them; rejects as soon as one rejects. Use it when you need every result.Promise.allSettled: waits for all and reports each outcome. Use it when some failures are acceptable.Promise.race: settles with the first one to settle, success or failure. Handy for timeouts.Promise.any: fulfils with the first success; rejects only if all fail.
Common mistakes
- Forgetting to return inside
.then. The next step receivesundefinedand runs before the inner work finishes. - Nesting promises like callbacks instead of returning them and chaining.
- Unhandled rejections: a chain with no
.catchhides errors (and Node.js treats them as fatal by default). - Thinking promises are lazy. The work starts when the promise is created, not when you call
.then.
What interviewers ask about promises
- "What are the three states of a promise?" Pending, fulfilled, rejected; once settled it never changes.
- "
Promise.allversusallSettled?" Fail fast versus collect every outcome. - "Implement
Promise.all." Keep a results array and a counter; resolve when the counter reaches the length; reject on the first error. - "When does a
.thencallback run?" As a microtask, after the current code finishes, never synchronously.
What should you learn before Promises?
What to learn after Promises
- Async/awaitasync/await is syntax on top of promises.
- Fetch APIThe standard way to make HTTP requests from JavaScript.
Connections to other concepts
- Part of
- JavaScript
Practise Promises
- Intermediate JavaScript Interview Questions3 questions on Promises
- Advanced JavaScript Interview Questions3 questions on Promises
- Top 20 JavaScript interview questions with answers: core JS, Node.js and React2 questions on Promises
- Intermediate Node.js Interview Questions1 question on Promises