Async Await

The time before generators and promises was a dark one. A time full of callbacks, and callbacks, and more callbacks. It was the nightmare of every developer and aspiring actress.

Then promises came and things started to look up in our world. Light returned to the lands again. The grasses were growing, frameworks were being created in the villages again. The world looked brighter. And it has only gotten brighter. Generators finally gave us a way to process async code in a way that felt like synchronous code.

Generators aren't perfect though. Managing promises with generators involves a lot of boilerplate and libraries. So the elders of the internet came together and proposed a solution. The boilerplate should become a built in standard called "async/await".

Async functions would a be a special kind of generator and await would be a special kind of yield that would pause and yield the result of a promise to the generator. Async code could then be clear and simple.

It looks like this:

const getCats = async() => {
  const result = await fetch('/cats.json')
}

To handle errors you just need to use a try and catch block, the same way you would handle errors in synchronous code. It looks like this:

const getCats = async() => {
  try {
    const result = await fetch('/cats.json')
  } catch (err) {
    console.log(err)
  }
}

Async functions compile to a wrapped generator. The first generator yields promises up to a parent generator which handles yielding the results of those promises back to the child generator.

You now know async!