13.8. A Promise: then chaining and handler timing
Topics
This question is in
13. Promise from scratchA promise is only useful if you can say "when it is done, do this". That is then. It takes two handlers, one for a value and one for a reason, and it returns a new promise for whatever the handler returns, which is what lets you write fetchUser().then(pickName).then(render) as a chain. Two details are easy to miss and matter in real code. Handlers never run during the call to then, even on a promise that has already settled: they run a moment later, as microtasks, in the order they were added. And a throw inside a handler is not a crash: it rejects the next promise in the chain.
This is the second of six problems that build a promise class. Write MyPromise in my-promise.js with its constructor (the rules of problem 13.7) and a then method.
Signature
class MyPromise {
constructor(executor) // as in problem 13.7
then(onFulfilled, onRejected) // returns a new MyPromise
}onFulfilled(value): called with the value if the promise fulfills.onRejected(reason): called with the reason if it rejects.- Either can be left out or be something that is not a function.
Requirements
- The constructor follows problem 13.7: it calls the executor at once with
resolveandreject; the promise settles only once; a throw in the executor rejects it. thenreturns a newMyPromiseon every call, never the same one.- When the promise fulfills,
onFulfilledis called with the value; when it rejects,onRejectedis called with the reason. Each is called at most once, with one argument, as a plain function (thisisundefined). - Handlers never run during the call to
thenor the call toresolve. Each runs as a microtask, queued when the promise settles (or, if it has already settled, whenthenis called), so it runs before a microtask queued after that moment. - Handlers on one promise run in the order
thenwas called, whether they were added before or after it settled. - What a handler returns fulfills the new promise, even when the handler was
onRejected. What a handler throws rejects the new promise. - A missing or non-function
onFulfilledpasses the value on to the new promise; a missing or non-functiononRejectedpasses the reason on. - A throw in one handler does not stop the other handlers of the same promise.
awaitworks on aMyPromise.- Do not use the built-in
PromiseinsideMyPromise: one test replaces it for a moment to check.
Examples
new MyPromise((resolve) => resolve(2))
.then((n) => n * 10)
.then((n) => console.log(n)); // 20const p = new MyPromise((resolve) => resolve("done"));
p.then((value) => console.log("handler", value));
queueMicrotask(() => console.log("microtask"));
console.log("sync");
// sync
// handler done
// microtasknew MyPromise((resolve, reject) => reject(new Error("no")))
.then((value) => console.log("skipped", value)) // no onRejected: the reason passes on
.then(null, (error) => `recovered from ${error.message}`)
.then(console.log); // "recovered from no"new MyPromise((resolve) => resolve(1))
.then(() => { throw new Error("bad"); })
.then(null, (error) => console.log(error.message)); // "bad"Environment
- Plain JavaScript in a browser page; the tests use the global class
MyPromise. They callthen, and usequeueMicrotaskandawaitto check when handlers run. - Use
queueMicrotaskto run handlers later; do not use the built-inPromiseorsetTimeoutfor that. - A handler that returns a promise or a thenable is out of scope here: in this stage the returned object is the value as it is. Following it is problem 13.11.
catchandfinallyare problems 13.9 and 13.10. Thestateandvaluegetters of problem 13.7 may stay; these tests do not use them.
Hints
- A handler added while the promise is pending must wait somewhere. Where, and who runs it when the promise settles?
- The new promise from
thenhas its ownresolveandreject. Which of them should the handler's return value and its throw go to? - Why is
setTimeout(handler, 0)too late, and what runs before the next timer?
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