DEV Community

Discussion on: Why to use async & await instead of the Promise class?

 
t7yang profile image
t7yang

Yes, catch is much more elegant.

Thread Thread
 
sinestrowhite profile image
SinestroWhite

Can you explain why there must be a try/catch block?

@Manuele J Sarfatti

Thread Thread
 
mjsarfatti profile image
Manuele J Sarfatti • Edited

In a classic promise you have:

const request = somePromise()
  .then(data => doSomethingWithData(data))
  .catch(error => doSomethingWithError(error))

If you switch to using await and you do:

const data = await somePromise()
doSomethingWithData(data)

but the promise fails (throws an exception), then you have yourself an unhandled exception, and the browser will most probably crash your app.

The equivalent of the classic promise is therefore:

try {
  const data = await somePromise()
  doSomethingWithData(data)
} catch (error) {
  doSomethingWithError(error)
}

PS: this is pseudo-code off the top of my head and most probably not working, it's just to give an idea