DEV Community

Discussion on: Explain Async/Await Like I'm Five

Collapse
 
qm3ster profile image
Mihail Malo

Gotchas

All throws in a function marked async are rejections, never throws from the initial function call.

const throws_fast = async () => {console.log('running');throw 'fast'}
let p
try {p = throws_fast()} catch (err) {console.log('synchronous catch')}
console.log('first catch over')
try {await p} catch (err) {console.log('awaited catch')}

This outputs

running <- so the body DID actually run synchronously on call
first catch over <- then things after the call
awaited catch <- and only in await we get the error

But this isn't always true for all Promise-returning functions!

const throws_fast = async () => {console.log('running');throw 'fast'}
const throws_fast_really = (fast) => {if (fast) throw 'really fast'; return throws_fast()}
let p
try {p = throws_fast_really()} catch (err) {console.log('synchronous catch')}
console.log('first catch over')
try {await p} catch (err) {console.log('awaited catch')}
console.log('second attempt!')
let p2
try {p2 = throws_fast_really(true)} catch (err) {console.log('synchronous catch')}
console.log('first catch over')
try {await p2} catch (err) {console.log('awaited catch')}
running
first catch over
awaited catch
second attempt!
synchronous catch
first catch over