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);
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
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 `catch'es
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
mdn
docs
A short description of how `catch` works.
spec
The actual chapter about `catch`, you need to dive in from here.
spec
The description of the actual flow of `catch`.