13.9. A Promise: catch and recovery
Topics
This question is in
13. Promise from scratchIn 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
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
- The constructor and
thenfollow problems 13.7 and 13.8: settle once, handlers as microtasks in order, return values and throws flow down the chain. p.catch(onRejected)does exactly whatp.then(undefined, onRejected)does. It works by callingthis.then(undefined, onRejected)and returning its result, so it also works on any object with athenmethod.- On a fulfilled promise,
catchpasses the value on and does not call its handler. - What the
catchhandler returns fulfills the next promise (recovery). What it throws rejects the next promise. - A rejection skips every
thenwithout a rejection handler, until the firstcatch(oronRejected). Acatchhandles only errors from before it in the chain. - Every reason counts as a rejection, even
undefined,0,""andnull. MyPromise.resolve(value)returnsvalueitself if it is aMyPromise; otherwise a newMyPromisefulfilled withvalue.MyPromise.reject(reason)returns a newMyPromiserejected withreason, as it is, even when the reason is aMyPromise.- Do not use the built-in
PromiseinsideMyPromise.
Examples
MyPromise.reject(new Error("offline"))
.then(() => console.log("skipped"))
.catch((error) => `cached copy (${error.message})`)
.then(console.log); // "cached copy (offline)"MyPromise.resolve(1)
.then(() => { throw new Error("step 2 failed"); })
.then(() => console.log("skipped"))
.catch((error) => console.log(error.message)); // "step 2 failed"MyPromise.reject("first")
.catch((reason) => { throw new Error(`still failing: ${reason}`); })
.catch((error) => console.log(error.message)); // "still failing: first"const p = MyPromise.resolve(5);
MyPromise.resolve(p) === p; // true
MyPromise.reject(p) === p; // false: p itself is the reasonEnvironment
- Plain JavaScript in a browser page; the tests use the global class
MyPromise. - Use
queueMicrotaskfor handler timing; do not use the built-inPromiseinsideMyPromise. - 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 thatMyPromise.resolvereturns aMyPromiseunchanged).finallyis problem 13.10.
Hints
- Which
thenfrom problem 13.8 already does everythingcatchneeds? - Why does
catchcallthis.theninstead 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