Very useful, thank you :) I was just a bit confused by this statement, it seems to contradict itself?:
"But the problem with the above module is that when we throw a new Error inside the then block of the promise, it will always pass to the catch block of the promise. That is because throwing a new error inside a then block of a promise will always be passed to the catch block of the invoking promise function."
I love learning, teaching and helping people with their code. I survive on coffee, and I've started to think that the bags under my eyes are also garbage collectors.
@fluffystark
pretty much answers your question. However, I'll explain it further just in case -
Say you have a promise function called somePromise. When you do a throw new Error() inside your .then() block, like below
try{somePromise().then((data)=>{thrownewError('Inner error');}).catch((promiseError)=>{console.log(promiseError);// Prints Inner error});}catch(error){// Handle all module errors here}
the error will get passed to the .catch() block of somePromise() and not the catch block of the try-catch.
When having multiple promise statements in your code, it can become cumbersome to handle each promise's errors in its own .catch() block. Using async/await allows you to handle all errors in one place. I hope this cleared your doubt. :)
I think the catch block it was referring to is the catch block right after the then block. But the goal was to have a single catch block do all the error handling but from that code, it had two catch blocks ( 1. for module errors, 2. for promise/then errors )
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Very useful, thank you :) I was just a bit confused by this statement, it seems to contradict itself?:
"But the problem with the above module is that when we throw a new Error inside the then block of the promise, it will always pass to the catch block of the promise. That is because throwing a new error inside a then block of a promise will always be passed to the catch block of the invoking promise function."
@fluffystark pretty much answers your question. However, I'll explain it further just in case -
Say you have a promise function called
somePromise
. When you do athrow new Error()
inside your.then()
block, like belowthe error will get passed to the
.catch()
block ofsomePromise()
and not thecatch
block of thetry-catch
.When having multiple promise statements in your code, it can become cumbersome to handle each promise's errors in its own
.catch()
block. Usingasync/await
allows you to handle all errors in one place. I hope this cleared your doubt. :)I think the catch block it was referring to is the catch block right after the then block. But the goal was to have a single catch block do all the error handling but from that code, it had two catch blocks ( 1. for module errors, 2. for promise/then errors )