Reputation: 6013
I was sitting in listening to a Javascript class today and they were covering something I hadn't seen before and which I don't fully understand. I will try to reproduce as best I can from memory
Instead of using the catch
of a Promise to handle errors, which I'm used to, the teacher used try...catch
wrapped around the Promise and its then
s. When I asked him why he did this, he said it was to catch the error 'synchronously'. That is, instead of the following format (I'm using pseudocode), which I'm used to
someLibrary.someFunctionThatReturnsAPromise
.then(() => something)
.then(() => somethingElse)
.catch(err => reportError)
he did it thus
try {
someLibrary.someFunctionThatReturnsAPromise
.then(() => something)
.then(() => somethingElse)
}
catch(err) {
reportError
}
What would be the difference between these two ways of catching the error? How would wrapping a Promise, which is asynchronous, report errors in a synchronous fashion?
Thanks for any insights!
Upvotes: 4
Views: 1831
Reputation: 63
Actually you can also you use 3 statement after catch - finally, but it depends )
Upvotes: 1
Reputation: 31983
The try-catch
won't catch asynchronous errors around a <somePromise>.then
since as you've noticed, the block will exit before the promise has finished/potentially thrown.
However, if you are using async
/await
then the try-catch
will catch since the block will wait for the await
:
async function foobar() {
try {
await doSomePromise();
} catch (e) {
console.log(e);
}
}
Upvotes: 3
Reputation: 370759
The try/catch
version will only catch the error if the error is thrown when the initial (synchronous) code is running - it will not catch errors that are thrown inside any of the .then
s:
try {
Promise.resolve()
.then(() => {
throw new Error()
});
} catch(e) {
console.log('caught');
}
So, the only way an error will be caught with try/catch
in your code is if someLibrary.someFunctionThatReturnsAPromise
throws synchronously. On the other hand, the .then
/.catch
version will catch any error (and is almost certainly preferable).
Upvotes: 1