Alan Plum
Alan Plum

Reputation: 10892

Synchronous exceptions in async functions

What happens if an async function throws an exception synchronously?

Example:

async function whatHappen () {
  throw new BombError()
  // no "await" here
}

try {
  whatHappen().catch(() => console.error('rejected'))
} catch (e) {
  console.error('thrown')
}

I've run this example in Babel and it seems that the throw is automatically caught and translated into a rejected promise, so the example will log "rejected" to the console.

But does this reflect the actual specification and how it will be implemented in JavaScript engines? I've tried reading the technical proposal but the specification is obviously not aimed at language users but language implementers.

Can I rely on async functions to always return a promise or are there situations where they might throw an exception synchronously? Is there any scenario where calling an async function without await should be wrapped in a try/catch block?

Upvotes: 2

Views: 583

Answers (1)

nils
nils

Reputation: 27184

Yes, an async function always returns a Promise.

In the technical proposal that you linked to, there is a sentence in the beginning stating that:

A similar proposal was made with Deferred Functions during ES6 discussions. The proposal here supports the same use cases, using similar or the same syntax, but directly building upon control flow structures parallel to those of generators, and using promises for the return type, instead of defining custom mechanisms.

(Emphasis mine)

So there is no case where you need to wrap an async function in a try/catch block, as it cannot throw a synchronous error.

PS: I just saw that Chrome Canary and MS Edge have implemented async/await behind a flag, so you could test it there as well.

Upvotes: 6

Related Questions