Sub topic 2
What a Promise Is: States and Settlement
This chapter assumes you are comfortable with JavaScript functions, closures and arrow functions. It also assumes you know what a callback is, how setTimeout schedules work for later, and how to run a script in Node.js or a browser console. The examples use new Promise(...) in its simplest form. The next chapter covers the constructor in detail. Here we only need it to produce promises in each state.
A promise is an object that stands in for a result that may not exist yet. When you call a function that returns a promise, you get the object right away. The actual value, or the error explaining why there is no value, arrives later. The promise records which of those outcomes happened and passes it to any code that asks.
That record follows a small, strict state machine. Knowing its rules lets you predict what then, catch, await and the combinators do in later chapters.
The Three States
Every promise is in exactly one of three states at any moment:
- Pending: the outcome is not known yet. This is where nearly every promise starts.
- Fulfilled: the operation succeeded, and the promise holds a value.
- Rejected: the operation failed, and the promise holds a reason, which is usually an
Errorobject.
A promise that is fulfilled or rejected is called settled. "Settled" just means "no longer pending". It does not name a fourth state.
| State | Settled? | What it holds | What happens to handlers |
|---|---|---|---|
| pending | No | Nothing yet | Stored until the promise settles |
| fulfilled | Yes | A value (any JavaScript value, including `undefined`) | Fulfillment handlers are scheduled with the value |
| rejected | Yes | A reason (any value, conventionally an `Error`) | Rejection handlers are scheduled with the reason |
The diagram has no arrow from fulfilled to rejected, from rejected to fulfilled, or from either one back to pending. Those transitions do not exist. This is the most important rule in the chapter.
Settlement Happens Once
When a promise settles, its state and its value or reason are fixed for good. Later attempts to resolve or reject it are ignored. They do not throw and they do not warn.
const p = new Promise((resolve, reject) => {
resolve('first');
resolve('second'); // ignored
reject(new Error('too late')); // ignored
});
p.then((v) => console.log(v)); // firstThis rule gives promises a guarantee that callbacks lack. A callback API with a bug might call your callback twice, or call it with both an error and a result. A promise can deliver only one outcome, and it delivers that outcome to every handler.
Because settlement is permanent, a promise also works as a cache. A handler attached long after settlement still receives the stored value:
const p = new Promise((resolve) => resolve(42));
setTimeout(() => {
p.then((v) => console.log('late subscriber got', v)); // late subscriber got 42
}, 1000);With an event emitter, a listener added after the event fires never hears it. A promise remembers its outcome, so the order in which you produce a result and subscribe to it stops mattering. Later chapters rely on this a lot: you can start several operations, keep their promises, and read the results whenever you like.
Seeing the State
The language has no public property for reading a promise's state synchronously. You cannot write if (p.state === 'fulfilled'). The only standard way to get the value is to register a handler with then or await, and the handler runs asynchronously.
For debugging, both major environments let you look inside. Browser dev tools show internal slots named [[PromiseState]] and [[PromiseResult]] when you log a promise. Node.js prints the state through util.inspect:
const util = require('node:util');
let resolveLater;
const pending = new Promise((resolve) => {
resolveLater = resolve;
});
const fulfilled = new Promise((resolve) => resolve(42));
const rejected = new Promise((_, reject) => reject(new Error('nope')));
rejected.catch(() => {}); // attach a handler so Node does not report an unhandled rejection
console.log(util.inspect(pending)); // Promise { <pending> }
console.log(util.inspect(fulfilled)); // Promise { 42 }
console.log(util.inspect(rejected).split('\n')[0]); // Promise { <rejected> Error: nope
resolveLater('later');
console.log(util.inspect(pending)); // Promise { 'later' }The last line shows that calling resolve with a plain value settles the promise immediately. The state changes synchronously. Only the handlers that react to the change run later, a timing detail covered in the chapter on the microtask queue.
Resolved Is Not the Same as Settled
The specification uses one more word that causes confusion: resolved. A promise is resolved once its fate is locked in, meaning that further calls to resolve or reject will be ignored. Usually resolving and settling happen at the same moment. They differ when you resolve a promise with another promise (or any thenable, an object with a then method).
In that case the outer promise does not fulfill with the inner promise as its value. It adopts the inner promise's outcome. Until the inner one settles, the outer one is resolved but still pending:
const util = require('node:util');
const inner = new Promise((resolve) => setTimeout(() => resolve('inner value'), 100));
const outer = new Promise((resolve, reject) => {
resolve(inner); // outer is now locked to inner
reject(new Error('ignored')); // too late: outer is already resolved
});
console.log(util.inspect(outer)); // Promise { <pending> }
setTimeout(() => {
console.log(util.inspect(outer)); // Promise { 'inner value' }
}, 200);The terms fit together like this:
| Term | Meaning |
|---|---|
| pending | Not yet fulfilled or rejected |
| settled | Fulfilled or rejected |
| resolved | Fate is fixed: either settled, or locked to follow another promise or thenable |
| unresolved | Pending and still free to be resolved or rejected |
You can also lock a promise to one that will reject. In that case calling resolve produces a rejected promise. The name resolve means "decide the fate", not "succeed". The thenables chapter explains how adoption works internally. For now the rule is that a promise never fulfills with another promise as its value.
What Settlement Does Not Do
Several mistakes come from expecting settlement to have side effects it does not have.
Calling resolve does not stop your code. resolve and reject are ordinary functions. They record the outcome and return undefined. The code after them keeps running:
new Promise((resolve) => {
resolve(1);
console.log('still runs'); // logs: still runs
throw new Error('swallowed'); // ignored: the promise is already fulfilled
}).then((v) => console.log('value:', v)); // value: 1A throw before settlement rejects the promise. A throw after settlement disappears silently, which can hide real bugs. If code after resolve must not run, write return resolve(value);.
Settlement does not cancel the underlying work. A promise only reports on an operation. It does not control the operation. If a timer or network request is still running when you lose interest, it keeps running. Cancellation has to come from the operation itself, for example through an AbortController passed to fetch.
Promises are not lazy. Creating a promise does not wait for someone to call then. The function passed to new Promise runs immediately, during construction. By the time you hold the promise, the work has already started. This differs from some other async abstractions, such as observables in RxJS, which do nothing until subscribed.
Pending is not a failure. A promise can stay pending forever if nothing ever resolves or rejects it. No timeout is built in. Any handlers attached to it never run, and await on it never continues. A promise that never settles is a common cause of "my code just stops" bugs.
Values and Reasons
A fulfillment value can be any JavaScript value: a number, an object, undefined or null. The one exception is a thenable, because resolving with a thenable triggers adoption rather than storing it.
A rejection reason can also be any value, and the language does not enforce Error objects. Rejecting with a string or a plain object is legal, but it loses the stack trace and breaks code that reads err.message. Reject with Error instances, or subclasses of Error, so that rejections look and behave like thrown exceptions.
// Legal but unhelpful: no stack trace, no .message
const bad = new Promise((_, reject) => reject('timeout'));
bad.catch((r) => console.log(typeof r, r)); // string timeout
// Preferred
const good = new Promise((_, reject) => reject(new Error('timeout')));
good.catch((e) => console.log(e instanceof Error, e.message)); // true timeoutA rejected promise also carries an obligation. If it settles as rejected and no rejection handler is ever attached, the runtime reports an unhandled rejection. In current Node.js versions that ends the process by default. This is why the inspection example above attached .catch(() => {}). The chapter on unhandled rejections covers the detection rules.
Summary of the Rules
- A promise starts pending and settles at most once, to fulfilled with a value or rejected with a reason.
- After settlement, the state and the value or reason never change, and later
resolveorrejectcalls are ignored. - Handlers attached after settlement still receive the stored outcome.
- Resolving with another promise or thenable locks the fate without settling. The outer promise follows the inner one.
- Settling does not stop the executor's code, cancel the work, or happen on demand. The work starts when the promise is created.
Exercise
What does this code log, and why? const p = new Promise((resolve, reject) => { reject(new Error('A')); resolve('B'); console.log('C'); }); p.then((v) => console.log('fulfilled', v), (e) => console.log('rejected', e.message));
Show answer
It logs "C" first, then "rejected A". The reject call settles the promise as rejected with Error('A'). The later resolve('B') is ignored because a settled promise never changes state. The executor keeps running after reject, so console.log('C') runs synchronously during construction. The handler runs afterwards, asynchronously, and receives the stored reason.
Exercise
A promise named outer is created with resolve(inner), where inner is a promise that rejects after one second. Immediately after construction, is outer pending, fulfilled or rejected? Is it resolved? What is its final state?
Show answer
Immediately after construction, outer is pending but resolved. Its fate is locked to inner, so any further resolve or reject calls are ignored. After one second, inner rejects and outer adopts that outcome, ending up rejected with the same reason. Calling resolve did not make outer succeed. It only fixed its fate.
Exercise
A colleague writes a cache that stores a promise for a config file and returns the same promise to every caller, including callers that arrive minutes after the file was loaded. They worry that late callers will miss the result. Are they right?
Show answer
No. A settled promise keeps its value or reason permanently, and a handler attached at any later time is still called with that stored outcome. Every caller gets the same result. One caveat is that if the load rejected, every later caller also gets that rejection. To retry, the cache has to replace the stored promise with a new one.