Noitidart Noitidart - 2 months ago 6
Javascript Question

Top promise .catch not triggered when returned child promise rejects

I have this:

function sayHello() {
return new Promise( resolve => {
throw new Error('reject');
});
}

new Promise(resolve => sayHello()).then(ok => console.log('ok:', ok)).catch( err => console.error('err:', err) );


However the
.catch
never triggers. I though if I return a promise within a promise, it gets chained so that top level
.then
and
.catch
are re-reouted to child
.then
and
.catch
?

Answer

The problem is with your "new error" thrown at the Promise callback. Throwing an error inside promise executor does not automatically reject it.
Edit: actually Promise executor does automatically reject the promise when an exception is thrown. Nevertheless, this is not the main cause of your problem. Also a note - throwing will only work on the "main" level of executor, so any asynchronous job throwing an exception won't automatically reject the promise.

Another problem spotted - your Promise chain (new Promise(resolve => sayHello())...) is also invalid - you are simply returning a function call result. You always have to manually resolve or reject a Promise that you've created with it's standard constructor (aka. new Promise(executorCallback)).

To fix the other problem, you can use "automatically resolved promise", which I think will do what you are trying to achieve:

Promise.resolve(sayHello()).then(...)

So in the end, your code should look like this (using the gist you have posted in the comment below by answer):

function sayHello() {
    return new Promise( (resolve,reject) => {
       reject('rawr')
    });
}

Promise.resolve(sayHello()).then(ok => console.log('ok:', ok)).catch( err => console.error('err:', err) );
Comments