jskatas.org Continuously Learn JavaScript. Your Way.

Promise: promise.catch()

Returns a Promise and deals with rejected cases only.

catch() returns a Promise and deals with rejected cases only

prerequisites for understanding

return a fulfilled promise, to pass a test
Promise.resolve(); assert(false); // Don't touch! Make the test pass in the line above!
reminder: the test passes when a fulfilled promise is returned
return Promise.reject('I should fulfill.');

catch method basics

is an instance method
const p = Promise; assert.equal(typeof p.catch, 'function');
catches only promise rejections
//: {"jskatas": {"runnerOptions": {"topLevelAwait": true}}} const promise = Promise.resolve(); await assert.rejects(promise);
returns a new promise
const whatToReturn = () => Promise.reject(); const promise = Promise.reject(); return promise.catch(() => whatToReturn() );
converts it`s return value into a promise
const p = Promise.reject(); const p1 = p.catch(() => void 0); return p1.then(result => assert.equal(result, 'promise?'));
the first parameter is the rejection reason
const p = Promise.reject('rejection'); return p.catch(reason => { assert.equal(reason, 'oops'); });

multiple catches

only the first catch is called
const p = Promise.reject('1'); const p1 = p .catch(reason => void 0) .catch(reason => `${reason} AND 3`) ; return p1.then(result => assert.equal(result, '1 AND 2') );
if a catch throws, the next catch catches it
const p = Promise.reject('1'); const p1 = p .catch(reason => { throw Error(`${reason} AND 2`) }) .catch(err => { throw Error(`${err.message} AND 3`) }) .catch(err => `${err} but NOT THIS`) ; return p1.then(result => assert.equal(result, '1 AND 2 AND 3') );

Links

A short description of how `catch` works.
The actual chapter about `catch`, you need to dive in from here.
The description of the actual flow of `catch`.

Required Knowledge

Related Katas

Promise

Difficulty Level

INTERMEDIATE

First Published

15 March 2015

Stats

9 tests to solve