Sub topic 13
Thenables and How Promises Adopt Other Promises
This chapter assumes you are comfortable with the Promise constructor, then chains, and the microtask queue covered in earlier chapters. It explains a behavior you have already relied on without seeing it: when you resolve a promise with another promise, or return a promise from then, the outer promise does not fulfill with the inner promise as its value. It adopts the inner promise's eventual state. The same mechanism works with any object that has a then method, which is why libraries written before native promises still work with await.
What a Thenable Is
A thenable is any object or function that has a callable then property. That is the whole definition. JavaScript does not check whether the object is a real Promise, where it came from, or whether its then behaves sensibly. If typeof x.then === 'function', the promise machinery treats x as something to wait on.
Every native promise is a thenable. Many other objects are thenables too: old jQuery Deferreds, Bluebird promises, query builders in database libraries such as Knex and Mongoose, and any object you write by hand.
const thenable = {
then(onFulfilled, onRejected) {
console.log('then called');
setTimeout(() => onFulfilled(42), 50);
},
};
Promise.resolve(thenable).then((v) => console.log('value:', v));
console.log('sync code done');
// sync code done
// then called
// value: 42 (after about 50 ms)Promise.resolve saw a callable then. It created a native promise, then called thenable.then with two functions that settle that native promise. When the thenable called onFulfilled(42), the native promise fulfilled with 42.
The log order shows that then called printed after sync code done. The engine does not call a thenable's then method synchronously. It schedules the call as a microtask. This protects your synchronous code from whatever the foreign then might do.
The Resolution Procedure
Each time a promise is resolved with a value x, the engine runs the same steps. This happens when you call resolve(x) in a constructor, return x from a then or catch handler, call Promise.resolve(x), or return x from an async function.
A few details in this procedure matter in practice.
thenis read exactly once. Ifthenis a getter, it runs one time, and the engine keeps the function it returned. A getter that throws rejects the promise.- Only the first call counts. The resolve and reject functions handed to the thenable work only once. Any later calls are ignored, which protects you from a buggy thenable that calls both.
- Resolution is recursive. If the thenable calls
resolveFnwith another thenable, the whole procedure runs again on that value. A promise for a promise for a promise ends up fulfilled with the innermost plain value. - Throwing inside
thenrejects, unless it is too late. If the thenable'sthenthrows after it has already calledresolveFn, the throw is ignored.
const messy = {
then(onFulfilled, onRejected) {
onFulfilled('first');
onFulfilled('second'); // ignored
onRejected(new Error('ignored')); // ignored
throw new Error('also ignored'); // ignored: already resolved
},
};
Promise.resolve(messy).then((v) => console.log(v)); // firstResolved Is Not the Same as Settled
Adoption explains a distinction the earlier chapter on states only hinted at. A promise is settled when it is fulfilled or rejected. A promise is resolved once its fate is locked in, and that can happen while it is still pending.
const delay = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
const outer = new Promise((resolve, reject) => {
resolve(delay(100, 'inner value')); // outer is now resolved, but still pending
resolve('ignored'); // too late: fate is locked in
reject(new Error('ignored')); // also too late
});
outer.then((v) => console.log(v)); // inner value (after about 100 ms)After the first resolve call, outer follows the delayed promise. It stays pending for 100 ms, yet nothing can redirect it. If the inner promise had rejected, outer would reject with the same reason. This is why resolving with a promise is safe: the outer promise mirrors the inner one exactly.
How the Entry Points Differ
| Operation | Given a native promise `p` | Given a non-promise thenable `t` | Given a plain value `v` |
|---|---|---|---|
| `Promise.resolve(x)` | Returns `p` itself, no new promise | New promise that adopts `t` | New promise fulfilled with `v` |
| `resolve(x)` in constructor | Adopts `p` | Adopts `t` | Fulfills with `v` |
| `return x` from `then` handler | Derived promise adopts `p` | Derived promise adopts `t` | Derived promise fulfills with `v` |
| `return x` from `async` function | Returned promise adopts `p` | Returned promise adopts `t` | Fulfills with `v` |
| `await x` | Waits on `p` directly | Wraps `t`, then waits | Wraps `v`, then waits |
| `Promise.reject(x)` | Rejects with `p` as the reason | Rejects with `t` as the reason | Rejects with `v` |
The first row has a shortcut. If x is a native promise built by the same constructor, Promise.resolve(x) === x. This makes Promise.resolve a cheap way to normalize a value that might or might not already be a promise.
const p = Promise.resolve(1);
console.log(Promise.resolve(p) === p); // true
console.log(new Promise((r) => r(p)) === p); // false: the constructor always makes a new promiseThe Cost of Adoption: Extra Microtasks
Adoption is not free. When a then handler returns a promise, the engine first queues a microtask to call that promise's then. Then it waits for another microtask, in which the inner promise's reaction resolves the outer one. Returning a promise therefore delays the next step by two extra ticks compared with returning a plain value.
Promise.resolve()
.then(() => {
console.log('a1');
return Promise.resolve(); // adoption: two extra microtasks
})
.then(() => console.log('a2'));
Promise.resolve()
.then(() => console.log('b1'))
.then(() => console.log('b2'))
.then(() => console.log('b3'))
.then(() => console.log('b4'));
// a1, b1, b2, b3, a2, b4Here is the tick-by-tick trace.
a1runs and returns a promise. The engine queues a job to call that promise'sthen.b1runs and queuesb2.- The job calls the inner promise's
then. The inner promise is already fulfilled, so a reaction is queued.b2runs and queuesb3. - The reaction resolves the derived promise, which queues
a2.b3runs and queuesb4. a2runs, thenb4.
await behaves differently. Since ES2019, await p on a native promise uses the Promise.resolve shortcut and subscribes to p directly, with no extra wrapping ticks. An await on a foreign thenable still takes the longer path.
Gotchas
Accidental thenables
Any object with a callable then gets assimilated, whether you meant it to or not. If its then never calls the callback it receives, the promise never settles.
async function getTask() {
return {
title: 'write docs',
then(next) {
// meant as "the task to run after this one", never calls next
},
};
}
getTask().then((task) => console.log(task.title)); // never logs
console.log('waiting forever...');The async function's returned promise tried to adopt the object, called its then, and waited for a callback that never came. A then property that is not a function, such as then: 'tomorrow', is harmless because the engine fulfills with the object as-is. Avoid naming a method then on anything that might pass through a promise. The same trap exists with dynamic import(): a module that exports a function named then makes await import('./mod.js') adopt that function instead of giving you the module namespace.
Self-resolution
A promise cannot adopt itself. Waiting for itself would deadlock, so the engine rejects with a TypeError instead. The error message differs between engines.
const p = Promise.resolve().then(() => p);
p.catch((err) => console.log(err instanceof TypeError, err.message));
// true Chaining cycle detected for promise #<Promise> (V8 wording)The engine detects only direct self-reference. Two promises that each resolve with the other just stay pending forever.
Lazy thenables
Some libraries make a query builder a thenable. The builder runs its query only when then is called. Awaiting it triggers execution, which is convenient. But awaiting the same builder twice may run the query twice, because each adoption calls then again. If you need the result more than once, convert it once with Promise.resolve(builder) and reuse that promise.
When to Use Thenables Deliberately
Normalize foreign values at a boundary. When a function might receive a value, a native promise, or a library's custom promise, Promise.resolve(input) gives you a native promise with standard behavior. That includes guaranteed asynchronous callbacks and one-time settlement.
Write your own thenable only when you have a clear reason. One example is a lazy object that should start work when it is awaited. In almost every other case, return a real promise. Native promises are faster to adopt, they integrate with unhandled-rejection tracking, and other developers expect them.
Exercise
What does this code log, and why? const t = { then(res) { res(Promise.resolve('deep')); } }; Promise.resolve(t).then(v => console.log(typeof v, v));
Show answer
It logs "string deep". Promise.resolve sees a callable then and calls it in a microtask. The thenable resolves with a native promise, and resolution is recursive, so the outer promise adopts that inner promise as well and fulfills with the plain string 'deep'.
Exercise
A colleague writes return Promise.reject(fetchUser()) to signal failure, where fetchUser() returns a promise. What reason does the resulting promise reject with, and how would you fix it?
Show answer
It rejects with the promise object returned by fetchUser(), because Promise.reject never adopts thenables. A catch handler would receive a Promise instead of an Error. To fail with an error, reject with an Error, for example return Promise.reject(new Error('user lookup failed')), or throw one inside a then handler or async function.
Exercise
Write a thenable that fulfills with the current time after a delay of ms milliseconds, and use it with await inside an async function.
Show answer
function later(ms) { return { then(onFulfilled) { setTimeout(() => onFulfilled(Date.now()), ms); } }; } async function main() { const t = await later(100); console.log('resolved at', t); } main(); The await wraps the thenable in a native promise, calls its then in a microtask, and resumes main when onFulfilled is called.