Skip to curriculum
Jump to the editor

13.12. A Promise that passes the full spec tests

Hard
Topics

This question is in

13. Promise from scratch
45–90 min

Promises/A+ is the open standard that made promises from different libraries work together, and the built-in Promise follows it. It pins down exactly three things: the states a promise can be in, how then behaves (when handlers run, how often, what the new promise gets), and the resolution procedure, which decides what happens when a promise is resolved with another promise or a thenable. A promise that follows all of it can be mixed freely with any other conforming promise, including await.

This is the last of six problems that build a promise class, and the one where it all has to work together. Write a complete MyPromise in my-promise.js, from scratch, that passes 40 tests drawn from those rules. The tests are our own; they cover the rules below one by one.

Signature

JAVASCRIPT
class MyPromise {
  constructor(executor)            // executor(resolve, reject), called at once
  then(onFulfilled, onRejected)    // returns a new MyPromise
  catch(onRejected)
  finally(onFinally)
  static resolve(value)
  static reject(reason)
}

Requirements

States

  1. A promise is pending, fulfilled or rejected. Once fulfilled it has a value, once rejected a reason, and neither ever changes; later calls to resolve or reject are ignored. A throw in the executor rejects the promise.

then

  1. Handlers that are not functions are ignored: then the new promise fulfills with the same value, or rejects with the same reason.
  2. onFulfilled runs after the promise fulfills, with the value as its only argument; onRejected after it rejects, with the reason. Never before, and at most once.
  3. Handlers never run during the code that called then or resolve. Each runs as a microtask, before any microtask queued after it became due; a handler added inside another handler still waits.
  4. Handlers are called as plain functions: this is undefined.
  5. then may be called many times on one promise; the handlers run in the order then was called. A handler that throws does not stop the others.
  6. then returns a new promise. A handler's return value resolves it (by the procedure below); a handler's throw rejects it with exactly what was thrown.

The resolution procedure, for resolving promise p with x:

  1. If x is p, reject with a TypeError.
  2. If x is not an object or a function (null included), fulfill with x.
  3. Otherwise read x.then once; if that throws, reject with the error; if it is not a function, fulfill with x.
  4. If it is a function, call it in a later microtask with x as this and two functions: resolvePromise(y) resolves p with y by these same rules; rejectPromise(r) rejects p with r, as it is.
  5. Only the first call of those two counts. A throw from then after one was called is ignored; before, it rejects p. A thenable that never calls either leaves p pending.

The rest of the class

  1. catch(f) is this.then(undefined, f). finally(f) runs f() with no arguments on either outcome, waits for any thenable it returns, and keeps the original outcome unless f throws or that thenable rejects. MyPromise.resolve(x) returns a MyPromise unchanged and otherwise resolves a new one with x; MyPromise.reject(r) returns a new promise rejected with r.
  2. Do not use or extend the built-in Promise. Use queueMicrotask for scheduling.

Examples

JAVASCRIPT
const p = new MyPromise((resolve) => resolve(1));
p.then((n) => n + 1).then((n) => console.log(n)); // 2
console.log("sync"); // printed first
JAVASCRIPT
const thenable = {
  then(resolvePromise, rejectPromise) {
    resolvePromise({ then: (inner) => inner("deep") }); // a thenable inside a thenable
    rejectPromise("ignored");                          // too late: the first call won
  },
};
MyPromise.resolve(thenable).then(console.log); // "deep"
JAVASCRIPT
const q = MyPromise.resolve().then(() => q);
q.catch((error) => console.log(error instanceof TypeError)); // true
JAVASCRIPT
(async () => {
  const value = await new MyPromise((resolve) => setTimeout(resolve, 50, "awaited"));
  console.log(value); // "awaited": await follows any thenable
})();

Environment

  • Plain JavaScript in a browser page; the tests use the global class MyPromise.
  • Each test builds its own promises with new MyPromise((resolve, reject) => ...); no adapter is needed.
  • Subclassing and unhandled-rejection reports are out of scope.

Hints

  1. Which rules belong to then, and which to the procedure that every resolve goes through? Keeping them apart keeps both short.
  2. A promise resolved with a pending promise is not settled yet, but it must ignore any later resolve or reject. What remembers that?

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…