13.12. A Promise that passes the full spec tests
Topics
This question is in
13. Promise from scratchPromises/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
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
- A promise is pending, fulfilled or rejected. Once fulfilled it has a value, once rejected a reason, and neither ever changes; later calls to
resolveorrejectare ignored. A throw in the executor rejects the promise.
then
- Handlers that are not functions are ignored: then the new promise fulfills with the same value, or rejects with the same reason.
onFulfilledruns after the promise fulfills, with the value as its only argument;onRejectedafter it rejects, with the reason. Never before, and at most once.- Handlers never run during the code that called
thenorresolve. Each runs as a microtask, before any microtask queued after it became due; a handler added inside another handler still waits. - Handlers are called as plain functions:
thisisundefined. thenmay be called many times on one promise; the handlers run in the orderthenwas called. A handler that throws does not stop the others.thenreturns 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:
- If
xisp, reject with aTypeError. - If
xis not an object or a function (nullincluded), fulfill withx. - Otherwise read
x.thenonce; if that throws, reject with the error; if it is not a function, fulfill withx. - If it is a function, call it in a later microtask with
xasthisand two functions:resolvePromise(y)resolvespwithyby these same rules;rejectPromise(r)rejectspwithr, as it is. - Only the first call of those two counts. A throw from
thenafter one was called is ignored; before, it rejectsp. A thenable that never calls either leavesppending.
The rest of the class
catch(f)isthis.then(undefined, f).finally(f)runsf()with no arguments on either outcome, waits for any thenable it returns, and keeps the original outcome unlessfthrows or that thenable rejects.MyPromise.resolve(x)returns aMyPromiseunchanged and otherwise resolves a new one withx;MyPromise.reject(r)returns a new promise rejected withr.- Do not use or extend the built-in
Promise. UsequeueMicrotaskfor scheduling.
Examples
const p = new MyPromise((resolve) => resolve(1));
p.then((n) => n + 1).then((n) => console.log(n)); // 2
console.log("sync"); // printed firstconst 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"const q = MyPromise.resolve().then(() => q);
q.catch((error) => console.log(error instanceof TypeError)); // true(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
- Which rules belong to
then, and which to the procedure that everyresolvegoes through? Keeping them apart keeps both short. - A promise resolved with a pending promise is not settled yet, but it must ignore any later
resolveorreject. 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