Is it possible to catch error from a promise without using await?

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?

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.

2 Likes

@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.

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.

:ok_hand: