A Promise is always in exactly one of three states. Understanding this state machine is the foundation for everything else.
The three states
- pending — initial state. The async operation has not completed yet. The Promise neither has a value nor a rejection reason.
- fulfilled — the operation completed successfully. The Promise has a value. This is also called "resolved" in some contexts.
- rejected — the operation failed. The Promise has a reason (usually an
Errorobject).
Once a Promise moves from pending to either fulfilled or rejected, its state is permanent. It can never go back to pending, and it can never switch between fulfilled and rejected. Fulfilled and rejected are collectively called settled.
The Promise constructor
You create a Promise by passing an executor function to new Promise(). The executor receives two functions: resolve and reject.
const p = new Promise((resolve, reject) => {
// This function is the "executor"
// It runs SYNCHRONOUSLY when new Promise() is called
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
resolve("operation succeeded"); // fulfills the Promise
} else {
reject(new Error("operation failed")); // rejects the Promise
}
}, 1000);
});The executor runs synchronously
This surprises many developers: the executor function runs immediately and synchronously when new Promise() is called. Only the callbacks registered with .then() are deferred.
let x = 0;
const p = new Promise(resolve => {
x = 1; // ← this runs NOW, synchronously
resolve(42); // ← this also runs NOW
});
console.log(x); // 1 — executor already ran by this line
p.then(v => console.log(v)); // logs 42 — but AFTER current synchronous code finishesresolve() with a thenable — Promise adoption
If you call resolve(value) and value is itself a Promise (or any thenable — an object with a .then method), the outer Promise adopts the state of that inner Promise rather than immediately fulfilling with it.
const inner = new Promise(resolve => setTimeout(() => resolve(99), 500));
const outer = new Promise(resolve => {
resolve(inner); // NOT fulfilled with inner as a value!
// outer ADOPTS inner's state — waits 500ms, then fulfills with 99
});
outer.then(v => console.log(v)); // 99 (not the Promise object)resolve() or reject() multiple times is a silent no-op after the first call. Only the first call matters: new Promise(resolve => { resolve(1); resolve(2); }) fulfills with 1 — the second call is ignored.