Async / await in ES7 - a practical example

The async / await feature of ES7 (JavaScript) will make asynchronous code more fun to read and write. The keywords are expected to become an official part of the language in Nov. 2016. Let's explore why they're important and how you might use them.

As a developer you do your best to ensure that functions are called correctly, in the appropriate order, but — much like a cheetah catching up to a gazelle — bad things can happen.

Managing asynchronous processes is one of the tougher aspects of learning JavaScript. When you finally master the concepts — functions as first-class citizens, promises, etc. — async is no longer a mystery...it's just a pain in the @!#. It can be frustrating to step through a web of callbacks or lengthy promise chains.

An upcoming feature in ES7 will make async operations sexier. I'm talking about the async and await keywords. As of now they are sugar: they don't change the way your browser interprets asynchronous function calls, but they make your async code appear synchronous.

Here's a practical use case:

  1. You need to retrieve a list of products along with customer preferences. This involves asynchronous requests to separate data sources.
  2. You want to combine the info to give the customer product recommendations.

If you're pressed for time, skip to showRecommendations. That's where the magic happens: handling asynchronous methods without promises or callbacks.

This code snippet is missing details that would be important in a real application. For example, it doesn't handle promise rejections. This is just a quick conceptual intro to async / await. The following articles offer a deeper dive into the topic.

Further Reading: