Promises
An object that represents a value you'll get later, not right now.
What is it?
Some tasks take time: fetching data, reading a file, waiting a few seconds. JavaScript can't just stop and wait, because that would freeze the page. It needs a way to say "start this, and tell me when it's done."
A Promise is an object for a value that isn't ready yet. It ends up either resolved (success) or rejected (failure). You say what to do in each case with .then() and .catch().
Explain like I'm 10
A promise is like a food delivery tracking number. You don't have the food yet, but you have something that stands for it, and you get told when it arrives or if the order fails.
Examples
Creating and using a promise
function waitOneSecond() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Done waiting!");
}, 1000);
});
}
waitOneSecond()
.then((message) => console.log(message)) // logs "Done waiting!" after 1s
.catch((error) => console.log("Something went wrong:", error));A promise that can reject
function fetchUser(id) {
return new Promise((resolve, reject) => {
if (id <= 0) {
reject(new Error("Invalid user id"));
return;
}
resolve({ id, name: "Amara" });
});
}
fetchUser(-1)
.then((user) => console.log(user))
.catch((error) => console.log("Failed:", error.message)); // "Failed: Invalid user id"reject(...) marks the promise as failed. Control jumps straight to .catch() and skips .then().
How it works
A promise starts out "pending". When the task finishes, it calls one of:
resolve(value): the promise becomes "fulfilled" and.then()callbacks run.reject(error): the promise becomes "rejected" and.catch()runs.
Once settled, the outcome never changes.
Promise created (pending)
↓
Task runs in the background
↓
┌───────┴───────┐
success failure
↓ ↓
resolve(value) reject(error)
↓ ↓
.then() runs .catch() runsWhy does it exist?
Before promises, running async steps in order ("fetch a user, then their orders, then the order details") meant deeply nested callbacks that were hard to read and easy to get wrong. Promises give async code one consistent shape and let you handle errors in one place.
When to use it
Use a promise for anything that finishes later (fetching data, reading a file, waiting on a timer) when you want a clear way to handle success and failure.
When not to use it
Don't wrap work that finishes instantly in a promise; it only adds overhead. In modern code you'll rarely write .then() chains by hand. Use async/await instead, and write raw promises mainly when building the underlying async function.
Common mistakes
Forgetting to add a
.catch(), so errors disappear silently.Nesting
.then()calls instead of chaining them, which brings back the mess promises were meant to fix.Forgetting to
returna value inside a.then(), so the next.then()gets nothing.
Practice exercises
- Easy:
Create a promise that resolves with your name after 500ms, and log it with
.then(). - Medium:
Create a promise that randomly resolves or rejects, and handle both cases.
- Hard:
Chain three promises together, each depending on the previous result, using
.then().
Interview questions
What are the three states a promise can be in, and can it move backward between them?
Pending, fulfilled and rejected. A promise only moves forward: pending to fulfilled, or pending to rejected. Once settled it stays there; it can't go back to pending or flip to the other outcome.
What's the difference between `.then()` and `.catch()`?
.then(onFulfilled, onRejected) can handle both outcomes. .catch(onRejected) is shorthand for .then(undefined, onRejected) and handles only rejection. .catch() is preferred because it also catches rejections and thrown errors from earlier .then() callbacks in the chain, not just the original promise.
What does `Promise.all()` do, and how does it behave if one promise rejects?
It takes an iterable of promises and returns one promise that fulfills with an array of all results, once every promise fulfills. If any promise rejects, Promise.all() rejects right away with that reason. It doesn't wait for the others, but their work keeps running because promises can't be cancelled.
What does `Promise.allSettled()` do, and how does it differ from `Promise.all()`?
It waits for every promise to settle and always resolves (never rejects) with an array of objects like {status: 'fulfilled', value} or {status: 'rejected', reason}. Unlike Promise.all(), one failure doesn't stop it; you get a report of every outcome.
What does `Promise.race()` do?
It returns a promise that settles as soon as the first input promise settles, with that promise's outcome, fulfilled or rejected. The rest are ignored.
What does `Promise.any()` do, and how is it different from `Promise.race()`?
It resolves as soon as the first promise fulfills and ignores rejections along the way. Unlike Promise.race(), one rejection doesn't end it. It only rejects if every promise rejects, with an AggregateError holding all the reasons.
You need to run four independent API calls and proceed only if all succeed, failing fast if any fails. Which combinator fits, and why not the others?
Promise.all(). It gives you all four results and rejects on the first failure, which matches 'all must succeed'. Promise.allSettled() doesn't fail fast because it waits for every call. Promise.race() and Promise.any() only care about one winner, not all four.
Once a promise has settled, can calling `resolve()` again change its value?
No. A promise settles only once. After the first resolve or reject call in the executor, later calls are silently ignored, so the outcome can't change.
What is a 'thenable', and why does it matter for promises?
Any object with a .then(onFulfilled, onRejected) method, even if it isn't a real Promise. Promise.resolve(thenable) and returning a thenable from a .then() callback both wait for it to settle instead of treating it as a plain value. That is how other libraries work with native promises.
What happens if you `return` a promise from inside a `.then()` callback?
The chain waits for the returned promise to settle, then passes its resolved value (not the promise) to the next .then(). This flattening lets you chain async steps instead of nesting promises.
Predict the output: a chain starts with `Promise.resolve(1)`, then adds 1, then throws inside the next `.then()`, then has a final `.then()` that logs, then a `.catch()` that logs the error message. What actually logs?
Only the .catch() log runs. The error thrown in the second .then() rejects the chain there. Every later .then() is skipped, since they only run on fulfillment, until the .catch() handles the rejection.
If you forget to add a `.catch()` to a chain that ends up rejecting, what actually happens?
It becomes an 'unhandled promise rejection'. In a browser this fires an unhandledrejection event and usually logs a warning. In Node.js it logs a warning by default and, depending on version and configuration, can crash the process. It is meant to surface as a bug, not be silently swallowed.
Can a `.catch()` handler catch an error thrown by an earlier `.then()` in the same chain?
Yes. A rejection or thrown error anywhere in a chain skips past every .then() until it reaches the next rejection handler (an onRejected argument or a .catch()). So one .catch() at the end can catch failures from any earlier step.
What does `.finally()` do, and does its callback receive the resolved value or rejection reason?
It runs after the promise settles, whatever the outcome, which is useful for cleanup like hiding a spinner. Its callback gets no arguments, and .finally() passes the original outcome through unchanged. The exception: if the callback throws or returns a rejected promise, that overrides it.
What's the difference between `Promise.resolve(x)` when `x` is a plain value versus when `x` is already a promise?
If x is a plain value, you get a new promise already fulfilled with it. If x is a promise or thenable, Promise.resolve(x) doesn't add another layer; it returns a promise that follows x's state. You never get a 'promise of a promise'.
Does the executor function passed to `new Promise((resolve, reject) => {...})` run immediately, or only once something calls `.then()`?
Immediately and synchronously, when the promise is constructed. Promises are eager, not lazy. .then() only controls when you hear about the result; it doesn't start the work.
Predict the output: a synchronous log, then constructing a `new Promise` whose executor logs synchronously before resolving, with a `.then()` attached, then a final synchronous log after the constructor call.
The order is: the first log, the executor's log, the final log, then the .then() log. The executor runs synchronously when the promise is created, but the .then() callback is queued as a microtask and runs after the current synchronous code finishes.
If the executor function passed to `new Promise()` throws synchronously, what happens to the promise?
The throw is caught automatically and treated like reject(error), so the promise is rejected with that error. You don't need a try/catch in the executor just to turn a synchronous throw into a rejection.
What happens if a `.then()` callback itself throws an error?
The promise returned by that .then() rejects with the error. It then travels down the chain like an explicit reject() until something catches it.
You call `.then()` twice on the same promise from two separate variables, instead of chaining them. Does the second `.then()` see the value transformed by the first?
No. Two .then() calls on the same promise create two independent branches, and both get the original resolved value. Only chaining, promise.then(...).then(...), passes a value from one step to the next.
How would you convert an older callback-style function into one that returns a promise?
Wrap the call in new Promise((resolve, reject) => {...}). The executor calls the original function, and its error-first callback calls reject on error or resolve otherwise. Node's built-in util.promisify does exactly this.
How would you add a timeout to a promise-based operation that might hang forever?
Use Promise.race() with the real operation and a promise that rejects after a setTimeout delay. Whichever settles first decides the outcome. The loser keeps running in the background because it can't be cancelled.
Since regular JavaScript promises can't be cancelled, how do people typically stop unneeded async work early anyway?
With a separate cancellation signal, usually AbortController/AbortSignal. The operation (like fetch) checks the signal and stops or rejects when told to abort. The promise itself never gets a real 'cancel' method.
What does `Promise.all()` resolve with when the input array mixes real promises with plain, non-promise values?
A plain value is treated as already resolved with itself. It appears in the results array next to the resolved values of the real promises, in the same position it was given.
Why does `Promise.any()` reject with an `AggregateError` instead of a single error?
It only fails when every input promise has rejected, so no single reason explains the failure. An AggregateError keeps all the rejection reasons in its .errors array, so nothing is lost.
You have three independent, unrelated async calls that don't depend on each other's results. What's wrong with awaiting them one at a time instead of using `Promise.all()`?
Awaiting them one at a time runs them in sequence, so the total time is roughly the sum of all three. Starting them together, for example with Promise.all(), runs them concurrently, so the total is closer to the slowest one.
What's the difference in behavior between attaching two separate `.then()` calls to the same promise versus chaining them?
Two separate .then() calls are independent listeners that both get the original resolved value. Chained, the second runs only after the first finishes and gets whatever the first returned.
Why is nesting `.then()` calls inside other `.then()` calls considered bad practice, even when it reaches the same result as a flat chain?
Nesting brings back the deeply indented, hard-to-follow code promises were meant to fix. Returning a promise from .then() and keeping the chain flat gives the same order, and keeps error handling in one .catch() instead of spread across nested blocks.
Does an error thrown inside a `.catch()` handler get caught by that same `.catch()`, or does it propagate further?
It propagates further down the chain. Like any .then() handler, .catch() returns a new promise. If its code throws, that promise rejects and needs its own later .catch().
How can you make sure an expensive async setup operation only actually runs once, even if multiple parts of the code request it around the same time?
Cache the promise itself the first time, not just its value, and give that same promise to every caller. A promise remembers its settled value and can have any number of .then() listeners, so every caller gets the one result and the work runs only once.
What does it mean, from the promise API's own perspective, that `.then()`/`.catch()`/`.finally()` callbacks always run as microtasks?
These callbacks never run synchronously, even for an already-settled promise. They always wait until the current code finishes, but run before anything else queued after that. That's why they run 'soon' but never in the middle of other running code.
Predict the output: two already-resolved promises each get a `.then(console.log)` attached, followed by a plain synchronous `console.log`.
The synchronous log runs first, then the two .then() callbacks in the order they were scheduled. Both are deferred as microtasks; being already resolved doesn't make .then() run synchronously.
You need to run a list of async tasks one at a time, in order, without async/await. How do you chain them dynamically using only promises?
Fold the array into one chain with reduce, starting from an already-resolved promise. Each step's .then() waits for the previous task before starting the next, giving a sequential chain for a list of any length.
Is there any meaningful difference between `Promise.resolve('done')` and manually writing `new Promise(resolve => resolve('done'))`?
Almost none: both give an already-fulfilled promise with the value 'done'. Promise.resolve() is just a shorter way to wrap a known value or existing thenable without writing an executor.