13.11. A Promise: adopting thenables
Topics
This question is in
13. Promise from scratchChains become useful when a step can itself be asynchronous: getUser().then((user) => getPosts(user.id)).then(render). The second step returns a promise, and the chain must wait for it and continue with its result, not with the promise object. The same happens with resolve(otherPromise) in an executor, and with await. This is called adopting a promise: the outer promise settles exactly the way the inner one does. It works for any thenable, any object or function with a then method, which is how promises from different libraries, and the built-in Promise, work together.
This is the fifth of six problems that build a promise class. Write MyPromise in my-promise.js with everything from problems 13.7 to 13.10, and make resolving follow promises and thenables.
Signature
class MyPromise {
constructor(executor) // resolve(x) now follows x when it is a thenable
then(onFulfilled, onRejected) // a handler's return value is followed too
catch(onRejected)
finally(onFinally) // waits for any thenable onFinally returns
static resolve(value) // follows a thenable; returns a MyPromise as it is
static reject(reason) // never follows
}Requirements
Resolving a promise p with a value x, through the executor's resolve, a handler's return value, or MyPromise.resolve, works like this:
- If
xispitself,prejects with aTypeError: a promise cannot wait for itself. - If
xis not an object or a function (includingnull),pfulfills withx. Primitives are never followed, even if someone adds athentoNumber.prototype. - Otherwise read
x.thenonce. If reading it throws,prejects with that error. If it is not a function,pfulfills withxitself. - If it is a function, call it in a later microtask (never during
resolve), withxasthisand two new functions,resolvePromiseandrejectPromise.resolvePromise(y)resolvespwithyby these same rules, so nested thenables are followed to the end;rejectPromise(r)rejectspwithr. - Only the first call among
resolvePromise,rejectPromisecounts. Ifthenthrows before either was called,prejects with the error; a throw after that is ignored. - Once
phas been resolved with a thenable, it is locked to it: the originalresolveandrejectare ignored from then on, even whilepis still pending. reject(x)never follows: the reason isxitself, even when it is a thenable.MyPromise.resolve(x)returnsxunchanged when it is aMyPromise, and otherwise a new promise resolved withxby these rules.finallywaits for any thenable thatonFinallyreturns, and keeps the original outcome unless that thenable rejects oronFinallythrows.- Everything from problems 13.7 to 13.10 still holds. Built-in promises work in both directions:
MyPromisefollows them, andawaitfollows aMyPromise. Do not use the built-inPromiseinsideMyPromise.
Examples
new MyPromise((resolve) => resolve(MyPromise.resolve("inner")))
.then(console.log); // "inner"const getPosts = (id) => new MyPromise((resolve) => setTimeout(resolve, 100, [`post of ${id}`]));
MyPromise.resolve(7)
.then((id) => getPosts(id)) // returns a promise: the chain waits for it
.then(console.log); // after 100 ms: ["post of 7"]const thenable = { then(onFulfilled) { onFulfilled("from a thenable"); } };
MyPromise.resolve(thenable).then(console.log); // "from a thenable"const p = MyPromise.resolve(1).then(() => p);
p.catch((error) => console.log(error instanceof TypeError)); // trueEnvironment
- Plain JavaScript in a browser page; the tests use the global class
MyPromise. - Use
queueMicrotaskfor all scheduling; do not use the built-inPromiseinsideMyPromise. The tests check when a thenable'sthenis called againstqueueMicrotask. - The
stateandvaluegetters may stay; whilepfollows a thenable, its state is still"pending". Subclasses are out of scope.
Hints
- "Settled" and "resolved" are no longer the same thing. What has to remember that
resolvewas already called, if the state is still pending? - A thenable's
thenmight call both of its functions, or call one twice. Where does the "first call wins" flag live, and why does each call tothenneed a fresh one? - Once a handler's return value is followed, how much shorter can
finallybecome?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it