Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onrejected vs catch in Promise [duplicate]

Tags:

What is the difference between catch and then(_,onRejected) in ES6 Promise? I just know that onRejected doesn't handle the rejected state of inner Promise.

Promise.resolve().then(() => {
    return new Promise((resolve,reject) => {
      throw new Error('Error occurs');
    }); 
},er => console.log(er)); //Chrome throws `Uncaught (in promise)`

Promise.resolve().then(() => {
    return new Promise((resolve,reject) => {
      throw new Error('Error occurs');
    }); 
}).catch(er => console.log(er)); //Error occurs
like image 401
Lewis Avatar asked Dec 05 '15 11:12

Lewis


People also ask

Does catch reject a Promise?

catch " around the executor automatically catches the error and turns it into rejected promise. This happens not only in the executor function, but in its handlers as well.

Can we use try catch inside Promise?

If you throw an error inside the promise, the catch() method will catch it, not the try/catch. In this example, if any error in the promise1, promise2, or promise4, the catch() method will handle it.

How do you throw a mistake from a Promise?

Any time you are inside of a promise callback, you can use throw . However, if you're in any other asynchronous callback, you must use reject . Instead you're left with an unresolved promise and an uncaught exception. That is a case where you would want to instead use reject .

Does Promise reject stop execution?

The reject function of a Promise executor changes the state of the Promise , but does not stop the executor. In general, it is recommended to add a return statement after the reject to stop unintended code execution.


Video Answer


1 Answers

Your first piece of code wont catch the error because the error handler is in the same .then where the error is thrown


As for your question

.catch(onRejected);

is identical to

.then(null, onRejected);

not sure what

.then(_, onRejected);

would do, depends on what _ is I guess

like image 78
Jaromanda X Avatar answered Sep 17 '22 14:09

Jaromanda X