JavaScriptFundamental (ES6), part 2
Promise chaining: what then() returns in JavaScript
30 What then does with what you return
fairFollow a value through a chain where one handler returns a plain value, one returns a promise, and one returns a thenable. Then check three identities: does then return a new promise, does Promise.resolve on a promise, and what does a non-function handler do?
Stuck? Three hints, smallest first
- 1. A returned value is wrapped. A returned promise is adopted, so the chain waits for it.
- 2. A thenable — any object with a
thenmethod — is adopted the same way. - 3.
then(null)is not an error. A non-callable handler is ignored and the value passes through.
const chained = await Promise.resolve(1)
.then((n) => n + 1) // a value is wrapped
.then((n) => Promise.resolve(n * 10)) // a promise is adopted
.then((n) => ({ then: (resolve) => resolve(n + 5) })); // a thenable, adopted too
const sameObject = (() => { const p = Promise.resolve(1); return p.then((x) => x) === p; })();
const resolveIsIdentity = (() => { const p = Promise.resolve(1); return Promise.resolve(p) === p; })();
const nested = await Promise.resolve(Promise.resolve('deep'));
const nothingReturned = String(await Promise.resolve(1).then(() => {}));
const ignoredHandler = await Promise.resolve('kept').then(null).then((v) => v);
const rounds = [];
Promise.resolve().then(() => rounds.push(1)).then(() => rounds.push(4)).then(() => rounds.push(6));
Promise.resolve().then(() => rounds.push(2)).then(() => rounds.push(5)).then(() => rounds.push(7));
Promise.resolve().then(() => rounds.push(3));
for (let i = 0; i < 8; i++) await Promise.resolve();
console.log('1 -> +1 -> x10 -> +5 =', chained);
console.log('then returns a new promise?', !sameObject, ' Promise.resolve is identity?', resolveIsIdentity);
console.log('returning nothing gives:', nothingReturned);
console.log('interleaving:', rounds);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a returned value is wrapped and flows on', chained, 25);
test('then always returns a NEW promise', sameObject, false);
test('but Promise.resolve on a promise returns that same promise', resolveIsIdentity, true);
test('a nested promise is flattened, not wrapped twice', nested, 'deep');
test('a thenable is adopted like a promise', await Promise.resolve({ then: (resolve) => resolve('thenable') }), 'thenable');
test('returning nothing gives undefined, not the previous value', nothingReturned, 'undefined');
test('a non-function handler is ignored and the value passes through', ignoredHandler, 'kept');
test('parallel chains advance one link per microtask round', rounds, [1, 2, 3, 4, 5, 6, 7]);
One rule explains most of this: whatever a handler returns is passed to Promise.resolve. A number comes back wrapped, a promise comes back as itself, and anything with a callable then is treated as a promise and waited for. That is why there is no such thing as a Promise<Promise<T>> — the fourth assertion is that impossibility in one line.
Thenable adoption is the useful and dangerous half. Useful, because a promise from a different library or an older polyfill interoperates with no adapter. Dangerous, because any object you resolve with is duck-typed: give a plain data object a property called then that happens to be a function and the promise will call it and wait, rather than handing your object over.
The last assertion is worth internalising for reading logs. Independent chains advance one link per microtask round, so three chains interleave 1 2 3, then 4 5, then 6 7. Output that looks shuffled usually is not — it is breadth-first through the chains.