JavaScript · The language round
How do promises work and what are their states?
Short answer
A promise is pending, then fulfilled or rejected, and that state never changes. then returns a new promise, which is how chaining and error recovery work.
A promise is a placeholder for a future value. The executor runs synchronously, but resolve and reject settle the promise asynchronously from the perspective of the code that consumes it.
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done"), 100);
});
promise
.then((value) => value.toUpperCase())
.then((value) => console.log(value))
.catch((error) => console.error(error))
.finally(() => console.log("settled"));The three states
- Pending: neither fulfilled nor rejected
- Fulfilled: settled with a value
- Rejected: settled with a reason, usually an Error
- Settled means fulfilled or rejected; it is not a fourth state
Once a promise settles, it cannot change. Calling resolve after reject has no effect. That immutability is what makes a promise safe to share.
Chaining
Each then returns a new promise. If the callback returns a value, the next promise fulfils with that value. If it returns a promise, the chain waits for it. If it throws, the next promise rejects and skips to the nearest catch.
Promise.resolve(2)
.then((value) => value * 3)
.then((value) => {
throw new Error("stopped");
})
.then(() => console.log("not reached"))
.catch((error) => console.log(error.message)); // "stopped"catch or use an async function with try/catch.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What are the three promise states?
- 2What does `then` return?
- 3Where should a `catch` be placed in a chain?
- 4What is the difference between `finally` and `then`?
- 5Can a settled promise change state again?
Say it in the interview
A promise starts pending and then becomes either fulfilled or rejected, and that state is permanent. then returns a new promise, so returning a value passes it to the next step, returning a promise waits for it, and throwing rejects the chain. catch handles a rejection, and finally runs regardless of outcome. If I do not handle a rejection, it becomes an unhandled rejection.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.