Skip to curriculum
Jump to the editor

13.9. A Promise: catch and recovery

Hard
Topics

This question is in

13. Promise from scratch
30–50 min

In real code, most chains end with one .catch: load, parse, render, and if anything along the way fails, show an error. That works because a rejection skips every step that has no rejection handler and lands at the first one that does. A catch can then do one of two things. It can recover, by returning a value, and the chain carries on as if nothing went wrong. Or it can rethrow, and the next catch gets the error. Knowing which one a handler does is the difference between a retry that works and an error that disappears.

This is the third of six problems that build a promise class. Write MyPromise in my-promise.js with its constructor and then (problems 13.7 and 13.8), and add catch and the two static helpers MyPromise.resolve and MyPromise.reject.

Signature

JAVASCRIPT
class MyPromise {
  constructor(executor)            // as in problem 13.7
  then(onFulfilled, onRejected)    // as in problem 13.8
  catch(onRejected)                // returns a new MyPromise
  static resolve(value)            // returns a MyPromise
  static reject(reason)            // returns a new MyPromise
}

Requirements

  1. The constructor and then follow problems 13.7 and 13.8: settle once, handlers as microtasks in order, return values and throws flow down the chain.
  2. p.catch(onRejected) does exactly what p.then(undefined, onRejected) does. It works by calling this.then(undefined, onRejected) and returning its result, so it also works on any object with a then method.
  3. On a fulfilled promise, catch passes the value on and does not call its handler.
  4. What the catch handler returns fulfills the next promise (recovery). What it throws rejects the next promise.
  5. A rejection skips every then without a rejection handler, until the first catch (or onRejected). A catch handles only errors from before it in the chain.
  6. Every reason counts as a rejection, even undefined, 0, "" and null.
  7. MyPromise.resolve(value) returns value itself if it is a MyPromise; otherwise a new MyPromise fulfilled with value.
  8. MyPromise.reject(reason) returns a new MyPromise rejected with reason, as it is, even when the reason is a MyPromise.
  9. Do not use the built-in Promise inside MyPromise.

Examples

JAVASCRIPT
MyPromise.reject(new Error("offline"))
  .then(() => console.log("skipped"))
  .catch((error) => `cached copy (${error.message})`)
  .then(console.log); // "cached copy (offline)"
JAVASCRIPT
MyPromise.resolve(1)
  .then(() => { throw new Error("step 2 failed"); })
  .then(() => console.log("skipped"))
  .catch((error) => console.log(error.message)); // "step 2 failed"
JAVASCRIPT
MyPromise.reject("first")
  .catch((reason) => { throw new Error(`still failing: ${reason}`); })
  .catch((error) => console.log(error.message)); // "still failing: first"
JAVASCRIPT
const p = MyPromise.resolve(5);
MyPromise.resolve(p) === p; // true
MyPromise.reject(p) === p;  // false: p itself is the reason

Environment

  • Plain JavaScript in a browser page; the tests use the global class MyPromise.
  • Use queueMicrotask for handler timing; do not use the built-in Promise inside MyPromise.
  • Following a promise or thenable passed to resolve, or returned from a handler, is problem 13.11; here such a value is kept as it is (except that MyPromise.resolve returns a MyPromise unchanged). finally is problem 13.10.

Hints

  1. Which then from problem 13.8 already does everything catch needs?
  2. Why does catch call this.then instead of reaching into private fields?

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…