What occurs if an async
function throws an exception synchronously?
For instance:
async function whatHappen () {
throw new BombError()
// no "await" here
}
try {
whatHappen().catch(() => console.error('rejected'))
} catch (e) {
console.error('thrown')
}
After testing this example in Babel, it appears that the throw
is automatically caught and translated into a rejected promise, resulting in the message "rejected"
being logged to the console.
However, does this accurately represent the official specification and how JavaScript engines will handle it? I attempted to understand the details from the technical proposal, but it is clear that the specification targets language implementers rather than users.
Is it a reliable assumption that async
functions will consistently return a promise, or are there situations where they could synchronously throw an exception? Are there any instances where calling an async function without await
necessitates the use of a try
/catch
block?