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
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.
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.
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With