Skip to curriculum
Jump to the editor

13.11. A Promise: adopting thenables

Hard
Topics

This question is in

13. Promise from scratch
30–50 min

Chains 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

JAVASCRIPT
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:

  1. If x is p itself, p rejects with a TypeError: a promise cannot wait for itself.
  2. If x is not an object or a function (including null), p fulfills with x. Primitives are never followed, even if someone adds a then to Number.prototype.
  3. Otherwise read x.then once. If reading it throws, p rejects with that error. If it is not a function, p fulfills with x itself.
  4. If it is a function, call it in a later microtask (never during resolve), with x as this and two new functions, resolvePromise and rejectPromise. resolvePromise(y) resolves p with y by these same rules, so nested thenables are followed to the end; rejectPromise(r) rejects p with r.
  5. Only the first call among resolvePromise, rejectPromise counts. If then throws before either was called, p rejects with the error; a throw after that is ignored.
  6. Once p has been resolved with a thenable, it is locked to it: the original resolve and reject are ignored from then on, even while p is still pending.
  7. reject(x) never follows: the reason is x itself, even when it is a thenable.
  8. MyPromise.resolve(x) returns x unchanged when it is a MyPromise, and otherwise a new promise resolved with x by these rules.
  9. finally waits for any thenable that onFinally returns, and keeps the original outcome unless that thenable rejects or onFinally throws.
  10. Everything from problems 13.7 to 13.10 still holds. Built-in promises work in both directions: MyPromise follows them, and await follows a MyPromise. Do not use the built-in Promise inside MyPromise.

Examples

JAVASCRIPT
new MyPromise((resolve) => resolve(MyPromise.resolve("inner")))
  .then(console.log); // "inner"
JAVASCRIPT
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"]
JAVASCRIPT
const thenable = { then(onFulfilled) { onFulfilled("from a thenable"); } };
MyPromise.resolve(thenable).then(console.log); // "from a thenable"
JAVASCRIPT
const p = MyPromise.resolve(1).then(() => p);
p.catch((error) => console.log(error instanceof TypeError)); // true

Environment

  • Plain JavaScript in a browser page; the tests use the global class MyPromise.
  • Use queueMicrotask for all scheduling; do not use the built-in Promise inside MyPromise. The tests check when a thenable's then is called against queueMicrotask.
  • The state and value getters may stay; while p follows a thenable, its state is still "pending". Subclasses are out of scope.

Hints

  1. "Settled" and "resolved" are no longer the same thing. What has to remember that resolve was already called, if the state is still pending?
  2. A thenable's then might call both of its functions, or call one twice. Where does the "first call wins" flag live, and why does each call to then need a fresh one?
  3. Once a handler's return value is followed, how much shorter can finally become?

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
Back to the question
Loading the editor…