JavaScriptFundamental (ES6), part 2
Unhandled promise rejections in JavaScript
25 Where a rejection goes when nobody is looking
fairReject a promise with no handler attached, then attach one later and show it still arrives. Work through what then and catch return, what a throw inside each becomes, and why a rejection can pass several links untouched.
Stuck? Three hints, smallest first
- 1. A rejection is a stored state, not an event. Nothing is thrown at the point of rejection.
- 2.
catch(fn)isthen(undefined, fn), and it returns a new, fulfilled promise if the handler returns normally. - 3.
thenwith only a success handler has nothing to catch with, so the rejection skips it.
const failed = Promise.reject(new Error('nobody is listening'));
let picked = '';
await Promise.resolve(); // a turn goes by, still unhandled
await failed.catch((e) => { picked = e.message; });
const secondLook = await failed.catch((e) => e.message);
const recovered = await failed.catch(() => 'recovered');
const carriedOn = await failed.catch(() => 0).then((n) => n + 1);
const throwInThen = await Promise.resolve(1).then(() => { throw new Error('thrown in then'); }).catch((e) => e.message);
const skipped = await Promise.reject(new Error('skipped past')).then(() => 'not run').catch((e) => e.message);
const throwInCatch = await Promise.reject(new Error('a')).catch(() => { throw new Error('b'); }).catch((e) => e.message);
const notAnError = await Promise.reject('just a string').catch((e) => [typeof e, e]);
console.log('picked up later :', picked);
console.log('and again :', secondLook);
console.log('catch recovers :', recovered, '-> chain continues:', carriedOn);
console.log('rejecting with a non-Error:', notAnError);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a rejection can be picked up later in the same tick', picked, 'nobody is listening');
test('the promise stays rejected, so a second handler sees it too', secondLook, 'nobody is listening');
test('catch returns a new promise that is FULFILLED with the handler result', recovered, 'recovered');
test('so the chain carries on after it', carriedOn, 1);
test('a throw inside then becomes the next rejection', throwInThen, 'thrown in then');
test('then with only a success handler passes a rejection straight through', skipped, 'skipped past');
test('a throw inside catch needs another catch', throwInCatch, 'b');
test('rejecting with a non-Error works, and loses the stack', notAnError, ['string', 'just a string']);
A rejection is a state a promise is in, not an event that fires. Nothing is thrown when Promise.reject runs; the reason sits there until something asks. That is why attaching a handler a turn later still works, and why the same promise can be handled twice.
What the runtime adds on top is a warning, not a mechanism: if the microtask queue drains and a rejected promise has still never been handled, Node prints an unhandled rejection and, since v15, exits non-zero. Browsers fire unhandledrejection on window. So "attach the handler later" works within the tick and is a bug across ticks.
The third assertion is the one people misread. catch does not mark a promise handled and leave it rejected — it returns a new promise that is fulfilled with whatever the handler returned. Which is exactly why .catch(() => {}) silently converts a failure into a success carrying undefined, and why the sixth assertion matters: a then without a second argument cannot swallow anything, so a rejection travels down a long chain untouched until it meets a real handler.
The last one is a habit worth keeping. throw new Error(...), never throw ‘string’. A string reason has no stack, no name and no cause, and every log line downstream is worse for it.