Promise States and Lifecycle
A JavaScript Promise starts in the `pending` state and eventually becomes either `fulfilled` or `rejected`. Once it is settled, its state cannot change again.
A Promise represents the eventual result of an asynchronous operation. Its initial state is `pending`, meaning the operation has not yet produced a final outcome.
Calling `resolve(value)` settles the Promise as `fulfilled`, while calling `reject(reason)` settles it as `rejected`. The fulfillment value or rejection reason becomes the result observed by handlers registered with `.then()`, `.catch()`, or `.finally()`.
A Promise is settled once it is fulfilled or rejected. Further attempts to resolve or reject the same Promise do not change its settled state or replace its stored result.
Promise handlers are scheduled asynchronously through the JavaScript job queue. This means attaching `.then()` or `.catch()` observes the Promise result without blocking the current synchronous execution.
Key points
- A Promise begins as `pending`.
- A pending Promise can settle as either `fulfilled` or `rejected`.
- A settled Promise cannot transition to another state.
- `resolve()` supplies the fulfillment value; `reject()` supplies the rejection reason.
- `.then()` handles fulfillment, `.catch()` handles rejection, and `.finally()` runs after settlement.
Interview questions
What are the three states of a JavaScript Promise?
A Promise starts in the `pending` state. It can then become `fulfilled` when the operation succeeds or `rejected` when it fails. Fulfilled and rejected are both settled states. Once settled, the Promise cannot change state again.
What happens if both `resolve()` and `reject()` are called for the same Promise?
Only the first effective settlement determines the Promise's state. If `resolve()` settles it first, a later `reject()` has no effect; the reverse is also true. This is part of the Promise's one-way state transition model.
What is the difference between a fulfilled Promise and a resolved Promise?
In everyday JavaScript discussion, 'resolved' is often used to mean that a Promise has been settled, but technically resolution is a procedure rather than simply a synonym for fulfillment. Resolving with another Promise can cause the outer Promise to adopt that Promise's eventual state. Therefore, a Promise can be resolved to a pending Promise and remain pending while it follows that outcome.
Why can't a Promise transition from fulfilled back to pending or rejected?
Promise state transitions are deliberately one-way so that an asynchronous result remains stable after it is observed. A pending Promise has not settled, so the first effective resolution determines its eventual settled outcome. Subsequent attempts do not mutate that state or replace its result.