aleen42
September 6, 2021, 2:13pm
1
As we known that, there is a difference between the following cases:
try { awat Promise.reject(1) } catch { console.log('caught') } // => "caught"
try { Promise.reject(1) } catch { console.log('caught') } // => throw "Uncaught (in promise) 1"
Is it possible to eliminate the difference?
ljharb
September 6, 2021, 4:28pm
2
Not in the language.
Both node and browsers provide an event listener for you to catch an unhandled rejection, but you can't handle that "synchronously" without await.
aleen42
September 7, 2021, 1:41am
3
@ljharb That may confuse someone that if an async function does not return a await promise, and we can't use try...catch statements to catch such a situation:
try { (async function f() { return await Promise.reject(1) })() } catch { console.log('caught') } // => "caught"
try { (async function f() { return Promise.reject(1) })() } catch { console.log('caught') } // => throw "Uncaught (in promise) 1"
In this case, we should use Promise.prototype.catch to catch any unhandled rejection, but I just want to know there is any other idea to eliminate the confusion.
ljharb
September 7, 2021, 1:52am
4
No, it's the responsibility of the creator of the Promise to ensure its errors are handled.
It's also perfectly fine for the author NOT to handle them - Promise.reject(); is a valid program.