Sub topic 13
Thenables and How Promises Adopt Other Promises
This chapter assumes you already know how to chain then calls, how errors travel through a chain, and that promise callbacks run as microtasks. In earlier chapters, returning a promise from a then handler made the chain wait for it. That waiting is called adoption, and it works for any object with a then method, not only real promises.
What a Thenable Is
A thenable is any object or function with a then method. The promise machinery does not check instanceof Promise. It looks for a callable then property. This duck typing let promise libraries such as Bluebird and jQuery Deferred work with native promises.
const thenable = {
then(onFulfilled, onRejected) {
setTimeout(() => onFulfilled(42), 50);
},
};
Promise.resolve(thenable).then((v) => console.log('adopted:', v)); // adopted: 42
Promise.resolve(1)
.then(() => thenable)
.then((v) => console.log('from chain:', v)); // from chain: 42
(async () => {
const v = await thenable;
console.log('awaited:', v); // awaited: 42
})();Promise.resolve, a value returned from a then handler, resolve(x) inside a constructor, and await all handle thenables the same way. The promise calls x.then(resolve, reject) in a fresh microtask and then settles however the thenable reports.
The Resolution Procedure
When a promise is resolved with a value x, the engine follows these steps:
Adoption is recursive. If the thenable fulfills with another thenable, that one is unwrapped too. A promise therefore never fulfills with a thenable as its value.
Gotchas
A broken then rejects the promise
If then throws before it calls either callback, the promise rejects with the thrown error. A throw that happens after the promise has settled is ignored, and so are any extra callback calls.
const bad = { then() { throw new Error('broken then'); } };
Promise.resolve(bad).catch((e) => console.log(e.message)); // broken then
const noisy = {
then(resolve, reject) {
resolve('first');
reject(new Error('ignored'));
throw new Error('also ignored');
},
};
Promise.resolve(noisy).then((v) => console.log(v)); // firstPromise.resolve may return the same object
Promise.resolve(p) returns p unchanged when p is a native promise with the same constructor. The constructor always creates a new promise that adopts p.
const p = Promise.resolve('x');
console.log(Promise.resolve(p) === p); // true
console.log(new Promise((r) => r(p)) === p); // falseResolving a promise with itself
A promise that adopts itself could never settle, so the engine rejects it with a TypeError.
let self;
self = new Promise((resolve) => setTimeout(() => resolve(self), 0));
self.catch((err) => console.log(err instanceof TypeError)); // trueAccidental thenables and extra ticks
An object you return from a handler gets unwrapped if it happens to have a then method. Avoid putting a then method on plain data objects. Adoption also adds microtask ticks: returning a promise from a then handler settles the outer promise about two ticks later than returning a plain value would. This only matters for code that depends on exact callback ordering, and you should not write code that depends on it.
| Input to `resolve` | Outcome |
|---|---|
| Plain value such as `5` or `{a: 1}` | Fulfills with that value |
| Native promise | Adopts its eventual state |
| Object with callable `then` | Calls `then` in a microtask and adopts the result |
| The promise itself | Rejects with `TypeError` |
| Object whose `then` getter throws | Rejects with that error |
Exercise
What does this log, and why? Promise.resolve({ then(res) { res({ then(r) { r('deep'); } }); } }).then((v) => console.log(typeof v, v));
Show answer
It logs "string deep". The outer thenable resolves with a second thenable. Adoption is recursive, so the promise unwraps that one as well and fulfills with the plain string 'deep'.
Exercise
A function returns { status: 'ok', then: 'later' } from a then handler. Does the chain treat it as a thenable?
Show answer
No. Its then property is a string, not a function, so the next handler receives the object unchanged as its value.