DEV Community

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

Collapse
 
miksimal profile image
Mikkel

I agree that in this case, there's no need for async/await, but whenenver you have logic that needs to happen between the async requests, it makes things so much cleaner.

E.g. I'm writing a Lambda that scrapes a website, then creates an Item to put into a DB, then makes the async db put:

module.exports.scraper = async event => {
  const response = await got(URL);
  // pick the HTML elements I want, e.g. top 10 headlines
  // create the Item I want to put into db (10 headlines plus a date, e.g.)
  return await client.put(params).promise();
}

Also agree with @leob though that understanding Promises is still super. You may well need to combine the two as well, e.g.

const getStuff = async () => {
  const thingOnePromise = axios.get('thingOneAPI');
  const thingTwoPromise = axios.get('thingTwoAPI');

  const [thingOne, thingTwo] = await Promise.all([thingOnePromise, thingTwoPromise])
  console.log(thingOne + " and " + thingTwo);
}

(similar example given by Wes Bos in his talk on async/await which I highly recommend: youtube.com/watch?v=DwQJ_NPQWWo)

Collapse
 
t7yang profile image
t7yang

I'm not a async await hater, for me they are isomorphic which can transform to each other. I even like to mix using promise and async await.

The main problem of this article is the examples to judge async await is better than promise is pretty bad one.

Thread Thread
 
mjsarfatti profile image
Manuele J Sarfatti

Also, why is no one ever bothered by having to add that try/catch block... I don't understand. I hate it.

Thread Thread
 
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