Excellent promise .catch does not work when returning a child’s promise is returned

I have it:

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 .catch never starts. Although, if I return the promise as part of the promise, it gets the chain so that the top level .then and .catch re-reentered for the child .then and .catch ?

+5
source share
1 answer

The problem is related to your “new error” caused by the Promise callback. Throwing an error inside the promise maker does not automatically reject it.
Edit: Actually, the Promise executor automatically rejects the promise when an exception is thrown. However, this is not the main cause of your problem. In addition, throwing a note will only work at the "main" level of the performer, so any asynchronous task that throws an exception will not automatically reject the promise.

Another problem - your Promise chain ( new Promise(resolve => sayHello())... ) is also not valid - you just return the result of the function call. You always have to manually allow or reject the promise that you created with the standard constructor (aka. new Promise(executorCallback) ).

To fix another problem, you can use the "automatically resolved promises" that 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 posted in the comment below):

 function sayHello() { return new Promise( (resolve,reject) => { reject('rawr') }); } Promise.resolve(sayHello()).then(ok => console.log('ok:', ok)).catch( err => console.error('err:', err) ); 
+4
source

Source: https://habr.com/ru/post/1257342/


All Articles