Sub topic 1
Recap: Pending, Fulfilled, Rejected
Every combinator in this tutorial takes a group of promises and returns one new promise. To predict what that new promise does, you need an exact picture of how a single promise behaves: which states it can be in, when it changes state, and what can go wrong along the way. This chapter goes over that model. It also covers a few details that the later chapters rely on, such as "settle once," the difference between resolving and fulfilling, and the fact that promises start their work as soon as they are created.
Prerequisites
This chapter assumes you are comfortable with the following:
- JavaScript functions, arrays, and destructuring
- Creating promises with
new Promise(...)and consuming them withthenandcatch asyncfunctions andawaittry/catcherror handling- The basic idea of the event loop: synchronous code runs to completion before queued callbacks run
The examples run in Node.js 18 or later. Most of them also run in a browser console.
The Three States
A promise is an object that stands for a result that may not exist yet. At any moment it is in exactly one of three states:
| State | Meaning | What it holds |
|---|---|---|
| pending | The operation has not finished | Nothing yet |
| fulfilled | The operation succeeded | A value |
| rejected | The operation failed | A reason (usually an `Error`) |
A promise that is either fulfilled or rejected is called settled. The combinator chapters use this word constantly. Promise.allSettled waits until every input is settled, and Promise.race follows the first input that settles, whether it fulfilled or rejected.
JavaScript does not let your code read a promise's state synchronously. You can only react to it through then, catch, finally, or await. Node's console does show the state, which is handy while debugging:
const pending = new Promise(() => {});
const fulfilled = Promise.resolve(42);
const rejected = Promise.reject(new Error('nope'));
rejected.catch(() => {}); // mark as handled so Node does not complain
console.log(pending); // Promise { <pending> }
console.log(fulfilled); // Promise { 42 }
console.log(rejected); // Promise { <rejected> Error: nope ... }A Promise Settles Only Once
Once a promise has settled, it stays that way. Any later calls to resolve or reject are ignored without an error, and so is a throw inside the executor after settlement.
const p = new Promise((resolve, reject) => {
resolve('first');
reject(new Error('ignored'));
resolve('also ignored');
throw new Error('ignored too');
});
p.then((value) => console.log(value)); // firstThe combinators are built on this rule. When Promise.race sees its first input settle, it settles its own output promise. Later inputs still settle and try to settle the output again, but those attempts do nothing. The same rule explains why the first rejection decides the result of Promise.all.
How a Promise Becomes Rejected
A promise is rejected in any of these ways:
- The executor calls
reject(reason). - The executor throws synchronously before settling. The thrown value becomes the reason.
- It is resolved with another promise that rejects (see the next section).
- For a promise returned by
thenorcatch, the handler throws or returns a rejected promise. - For a promise returned by an
asyncfunction, the function body throws or awaits a promise that rejects without catching it.
const thrown = new Promise(() => {
throw new Error('executor threw');
});
thrown.catch((err) => console.log(err.message)); // executor threw
async function failing() {
await Promise.resolve();
throw new Error('async function threw');
}
failing().catch((err) => console.log(err.message)); // async function threwYou can reject with any value, including a string or undefined. Rejecting with an Error is still the convention, because it carries a stack trace and a message. The combinator examples later read err.message, and that only works when the reasons are Error objects.
Resolving Is Not the Same as Fulfilling
The function is named resolve, but calling it does not always fulfill the promise. If you pass it a plain value, the promise fulfills with that value. If you pass it another promise, or any thenable (an object with a then method), the outer promise follows that inner one and copies whatever state it ends up in.
const inner = new Promise((_, reject) => {
setTimeout(() => reject(new Error('inner failed')), 50);
});
const outer = new Promise((resolve) => {
resolve(inner); // outer now follows inner
});
outer.then(
(value) => console.log('fulfilled:', value),
(err) => console.log('outer rejected:', err.message)
);
// after about 50 ms: outer rejected: inner failedSo a promise that has been "resolved" may still be pending, and it may end up rejected. Promise.resolve(x) follows the same rule. It wraps a plain value in a fulfilled promise, returns x unchanged if x is already a native promise, and follows x if it is a thenable.
This matters for the combinators. Each one runs its inputs through Promise.resolve, which is why you can pass plain values like 3 alongside real promises. The edge-cases chapter covers that behavior in detail.
Handlers Run Asynchronously
Even when a promise is already settled, its then callbacks never run immediately. They are placed on the microtask queue, which the engine drains after the current synchronous code finishes and before it runs timers or I/O callbacks.
console.log('1 sync start');
Promise.resolve('value').then((v) => console.log('3 then callback:', v));
setTimeout(() => console.log('4 timeout'), 0);
console.log('2 sync end');
// 1 sync start
// 2 sync end
// 3 then callback: value
// 4 timeoutBecause of this, a combinator never settles synchronously either. Promise.all([]) with an empty array still hands its result to your code on a later microtask.
Promises Start Work When They Are Created
A promise does not represent a task waiting to be started. The executor runs synchronously inside new Promise(...), and functions that return promises, such as fetch or an async function, begin their work when you call them. await does not start anything. It only waits for something that is already running.
function task(name, ms) {
console.log(`start ${name}`);
return new Promise((resolve) => {
setTimeout(() => {
console.log(`done ${name}`);
resolve(name);
}, ms);
});
}
const a = task('a', 100);
const b = task('b', 50);
a.then((value) => console.log('a value:', value));
b.then((value) => console.log('b value:', value));
// start a
// start b
// done b
// b value: b
// done a
// a value: aBoth timers started before either result was used. This is the basis for the next chapter: by the time you pass an array of promises to Promise.all, the operations are already running at the same time. The combinator only decides how to wait for them. It cannot start, pause, or cancel them.
Each then Returns a New Promise
then, catch, and finally each return a new promise, and the handler decides how it settles:
| Handler does this | Returned promise |
|---|---|
| Returns a plain value | Fulfills with that value |
| Returns a promise or thenable | Follows it |
| Throws | Rejects with the thrown value |
| No handler for this outcome | Passes the same value or reason through |
The last row explains why one catch at the end of a chain handles a rejection from any earlier step. It also explains why a catch that logs an error and returns nothing turns a rejection into fulfillment with undefined. That mistake is easy to make when you wrap individual inputs before passing them to Promise.all.
Unhandled Rejections
A rejected promise with no rejection handler attached by the end of the current microtask turn is reported as an unhandled rejection. Since Node.js 15, the default response is to crash the process. Browsers log an error to the console.
A common way to get this wrong is to create a promise, await something slow first, and only then await the promise:
async function risky() {
const willFail = Promise.reject(new Error('early failure'));
await new Promise((resolve) => setTimeout(resolve, 100)); // no handler on willFail yet
try {
await willFail;
} catch (err) {
console.log('caught too late:', err.message);
}
}
risky();
// Node reports an unhandled rejection before the catch runsPassing both promises to Promise.all at the same time fixes this, because it attaches handlers to both right away.
Summary
- A promise is pending, fulfilled (with a value), or rejected (with a reason). Fulfilled and rejected together are called settled.
- A promise settles once. Later attempts to settle it are ignored, but the underlying work keeps running.
- Resolving with a promise or thenable makes the outer promise follow it, so a resolved promise can still reject.
- Handlers always run asynchronously, as microtasks.
- Promises start their work when they are created.
awaitand the combinators only wait.
Exercise
What does this code log, and in what order? const p = new Promise((resolve, reject) => { console.log('A'); resolve(Promise.reject(new Error('B'))); reject(new Error('C')); }); p.catch((e) => console.log(e.message)); console.log('D');
Show answer
It logs A, then D, then B. The executor runs synchronously, so A comes first. Calling resolve with a rejected promise makes p follow that promise, and the later reject(new Error('C')) is ignored because p is already resolved. The catch handler runs asynchronously after the synchronous console.log('D'), and it receives the reason of the followed promise, which is B.
Exercise
A colleague writes const users = fetchUsers(); const orders = fetchOrders(); const u = await users; const o = await orders; and says the two requests run one after the other because of the two awaits. Are they right?
Show answer
No. Both requests start when fetchUsers() and fetchOrders() are called, before either await runs, so they run at the same time. The awaits only wait for the results. The code does carry a risk, though: if orders rejects while the code is still waiting on users, the orders rejection has no handler yet and may be reported as unhandled. Promise.all([users, orders]) avoids that.
Exercise
What does Promise.resolve(1).then(() => { throw new Error('x'); }).catch(() => {}).then((v) => console.log(v)) log, and why?
Show answer
It logs undefined. The first then handler throws, so its returned promise rejects. The catch handler handles the rejection and returns nothing, so the promise it returns fulfills with undefined. The last then receives that value.