The Three States and the Promise Object
A promise is an ordinary object with a state and a value, and watching it change state is the fastest way to stop it feeling abstract.
A promise is pending, fulfilled or rejected. It settles exactly once and never changes again. It is a real object you can log and inspect, holding a result nobody can reach except through then or await.
EXERCISE
1A Promise Is an Object You Can Look At
The word suggests something abstract, and the thing itself is a value sitting in a variable with properties you can inspect.
Before any of the syntax, it helps to see that a promise is not a special language construct. It is an object. You can store it, log it, pass it to a function, put it in an array.
Log one and see what it is:
const p = fetch("https://api.example.com/user");
console.log(p);
// Promise { <pending> }
console.log(typeof p);
// "object"
console.log(p instanceof Promise);
// true
fetch did not return the user. It returned an object that will eventually hold the user, and handed it back immediately so your code could carry on.
Watch it change:
const p = new Promise((resolve) => {
setTimeout(() => resolve("done"), 1000);
});
console.log(p);
// Promise { <pending> }
setTimeout(() => {
console.log(p);
// Promise { 'done' }
}, 1500);
The same object, logged twice. In between it moved from pending to fulfilled and took on a value. Nothing replaced it; its internal state changed.
Those internals are genuinely internal:
const p = Promise.resolve(42);
console.log(Object.keys(p)); // []
console.log(Object.getOwnPropertyNames(p)); // []
console.log(p.value); // undefined
A browser console will show you [[PromiseState]] and [[PromiseResult]] in double brackets, which marks them as specification internals rather than properties. You cannot read the value with a property access. The only ways in are .then and await, and that is deliberate: it forces the value to be handled asynchronously, which is the one thing that makes the timing predictable.
And the object is what gets passed around:
function loadUser() {
return fetch("/api/user");
}
const pending = loadUser();
const all = [loadUser(), loadUser(), loadUser()];
None of those lines waited. Each produced an object. Unit 4's rule still holds: nothing here blocks the stack.
Pro Tip: When async code confuses you,
console.logthe promise itself rather than the value you expect. SeeingPromise { <pending> }where you expected data tells you immediately that you forgot anawaitor a.then, and it is by far the fastest diagnosis for the single most common async mistake.
EXERCISE
2Three States, One Transition
A promise starts pending and moves once, which is a stronger guarantee than it first appears.
The three states:
// PENDING the starting state, nothing decided
// FULFILLED settled with a value
// REJECTED settled with a reason, usually an Error
// A promise is "settled" once it is fulfilled or rejected.
// Pending -> fulfilled, or pending -> rejected. Never back.
// Never fulfilled -> rejected. Never settled twice.
The one-transition rule, demonstrated:
const p = new Promise((resolve, reject) => {
resolve("first");
resolve("second");
reject(new Error("too late"));
});
p.then((value) => {
console.log(value); // first
});
Three attempts to settle it, one winner. The second resolve and the reject are ignored entirely, silently and by design. No error, no warning.
This matters more than it sounds. It means a promise handed to you cannot change its mind, so you can attach a handler whenever you like without racing anything.
Including after it has already settled:
const p = Promise.resolve("ready");
setTimeout(() => {
p.then((v) => console.log(v)); // ready
}, 1000);
Attaching a handler a second late still works. The promise kept its value, and the handler is queued as a microtask immediately. Compare that with an event listener, which only hears events that happen after you attach it. A promise is a value that arrives once; an event is a stream you can miss.
And a handler always runs asynchronously, even when nothing was async:
console.log("before");
Promise.resolve("value").then((v) => console.log(v));
console.log("after");
// before
// after
// value
Promise.resolve is already settled, so this could in principle run immediately. It does not. Every .then callback goes through the microtask queue from Unit 4, without exception. That consistency is the point: a function that sometimes calls back synchronously and sometimes asynchronously is far harder to reason about than one that always does the same thing.
"Settles once and never changes" is the guarantee to hold on to. It is what makes a promise safe to store, to return from a cache, to hand to three different callers, and to attach a handler to long after the work has finished. None of that is safe with a callback or an event.
EXERCISE
3What Promises Replaced
The problems promises solve are easier to see in the code that came before them.
Promises are not a nicer way to write callbacks. They fix two specific problems that callbacks had, and both are worth seeing.
Problem one: nesting, when each step depends on the last.
getUser(id, (err, user) => {
if (err) {
return handle(err);
}
getPosts(user.id, (err, posts) => {
if (err) {
return handle(err);
}
getComments(posts[0].id, (err, comments) => {
if (err) {
return handle(err);
}
render(comments);
});
});
});
Three sequential steps, and the code drifts rightwards with an error check repeated at every level. This shape has a name, the pyramid of doom, and the problem is not that it is ugly. It is that the error handling is duplicated and easy to get subtly wrong at one level out of five.
The same thing as a chain:
getUser(id)
.then((user) => getPosts(user.id))
.then((posts) => getComments(posts[0].id))
.then((comments) => render(comments))
.catch(handle);
Flat, and one error path for all of it. That is the rejection-skipping rule from lesson 3 doing the work that three if (err) blocks were doing before.
Problem two, which is subtler: you lose control of your own callback.
processPayment(amount, (result) => {
chargeCustomer(result);
});
You have handed your function to processPayment and you are now trusting it completely. Does it call back once? Could it call twice, double-charging? Could it never call back at all? Could it call back synchronously sometimes and asynchronously other times?
You cannot tell by looking, and if processPayment is a third-party library you cannot tell at all. This is called inversion of control: the decision about when and how often your code runs has moved to code you do not own.
A promise takes that control back:
const result = await processPayment(amount);
chargeCustomer(result);
The guarantees from lesson 1 now apply. It settles once, so your handler cannot run twice. It always resolves asynchronously, so the timing is consistent. And you attach the handler, rather than handing a function over and hoping.
Neither problem was about syntax. Nesting made errors easy to mishandle, and inversion of control made behaviour impossible to verify. The flatter code is a pleasant consequence.
