Skip to curriculum
Jump to the editor

13.8. A Promise: then chaining and handler timing

Hard
Topics

This question is in

13. Promise from scratch
30–50 min

A 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

JAVASCRIPT
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

  1. The constructor follows problem 13.7: it calls the executor at once with resolve and reject; the promise settles only once; a throw in the executor rejects it.
  2. then returns a new MyPromise on every call, never the same one.
  3. When the promise fulfills, onFulfilled is called with the value; when it rejects, onRejected is called with the reason. Each is called at most once, with one argument, as a plain function (this is undefined).
  4. Handlers never run during the call to then or the call to resolve. Each runs as a microtask, queued when the promise settles (or, if it has already settled, when then is called), so it runs before a microtask queued after that moment.
  5. Handlers on one promise run in the order then was called, whether they were added before or after it settled.
  6. What a handler returns fulfills the new promise, even when the handler was onRejected. What a handler throws rejects the new promise.
  7. A missing or non-function onFulfilled passes the value on to the new promise; a missing or non-function onRejected passes the reason on.
  8. A throw in one handler does not stop the other handlers of the same promise.
  9. await works on a MyPromise.
  10. Do not use the built-in Promise inside MyPromise: one test replaces it for a moment to check.

Examples

JAVASCRIPT
new MyPromise((resolve) => resolve(2))
  .then((n) => n * 10)
  .then((n) => console.log(n)); // 20
JAVASCRIPT
const p = new MyPromise((resolve) => resolve("done"));
p.then((value) => console.log("handler", value));
queueMicrotask(() => console.log("microtask"));
console.log("sync");
// sync
// handler done
// microtask
JAVASCRIPT
new 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"
JAVASCRIPT
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 call then, and use queueMicrotask and await to check when handlers run.
  • Use queueMicrotask to run handlers later; do not use the built-in Promise or setTimeout for 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. catch and finally are problems 13.9 and 13.10. The state and value getters of problem 13.7 may stay; these tests do not use them.

Hints

  1. A handler added while the promise is pending must wait somewhere. Where, and who runs it when the promise settles?
  2. The new promise from then has its own resolve and reject. Which of them should the handler's return value and its throw go to?
  3. 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
Back to the question
Loading the editor…