Javascript Async Await

javascript

https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9
https://www.twilio.com/blog/2015/10/asyncawait-the-hero-javascript-deserved.html
https://blog.lavrton.com/javascript-loops-how-to-handle-async-await-6252dd3c795

https://davidwalsh.name/async-await
https://coligo.io/javascript-async-await/
https://tutorialzine.com/2017/07/javascript-async-await-explained

https://ponyfoo.com/articles/understanding-javascript-async-await
https://javascript.info/async-await
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
https://stackoverflow.com/questions/46438711/using-async-await-with-ajax

How can we use async and await?

Assuming a function getJSON that returns a promise, and that promise resolves with some JSON object. We just want to call it and log that JSON, then return "done". This is how you would implement it using promises:

const makeRequest = () =>
  getJSON()
    .then(data => {
      console.log(data)
      return "done"
    })

makeRequest()

And this is how it looks with async/await:

const makeRequest = async () => {
  console.log(await getJSON())
  return "done"
}

makeRequest()

There are a few differences here:

  1. Our function has the keyword async before it. The await keyword can only be used inside functions defined with async. Any async function returns a promise implicitly, and the resolve value of the promise will be whatever you return from the function (which is the string "done" in our case).
  2. The above point implies that we can’t use await in the top level of our code since that is not inside an async function.
// this will not work in top level
// await makeRequest()

// this will work
makeRequest().then((result) => {
  // do something
})

await getJSON() means that the console.log call will wait until getJSON() promise resolves and print it value.

How can we handle exception using async and await?

Async/await makes it finally possible to handle both synchronous and asynchronous errors with the same construct, good old try/catch. In the example below with promises, the try/catch will not handle if JSON.parse fails because it’s happening inside a promise. We need to call .catch on the promise and duplicate our error handling code, which will (hopefully) be more sophisticated than console.log in your production ready code.

const makeRequest = () => {
  try {
    getJSON()
      .then(result => {
        // this parse may fail
        const data = JSON.parse(result)
        console.log(data)
      })
      // uncomment this block to handle asynchronous errors
      // .catch((err) => {
      //   console.log(err)
      // })
  } catch (err) {
    console.log(err)
  }
}

Now look at the same code with async/await. The catch block now will handle parsing errors:

const makeRequest = async () => {
  try {
    // this parse may fail
    const data = JSON.parse(await getJSON())
    console.log(data)
  } catch (err) {
    console.log(err)
  }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License