Tip 44: Create Clean Functions with Async/Await

In this tip, you’ll learn how to streamline promises with async/await.

In the previous tip, you saw that promises are awesome. They’re a vast improvement over callbacks, but their interfaces are still a little clunky. You’re still working with callbacks in methods. Fortunately, the language continues to improve. You can now avoid callbacks entirely by adding asynchronous promise data to a variable in a single function.

async & await

Developers usually talk about the new syntax, async/await, as a group, but it’s really two separate actions. You use the async keyword to declare that an encapsulating function will be using asynchronous data. Inside the asynchronous function, you can use the await keyword to pause the function until a value is returned.

Before you begin, there are a couple things to note.

  • First, this doesn’t replace promises. You’re merely wrapping promises in a better syntax.

  • Second, it isn’t well supported, and the compiled code is a little buggy. It’s safe to use on server-side JavaScript, but you may have problems in browsers.

Example

To see async/await in action, refactor some of your code from the previous tip. As a reminder, you pass a function to the then() method on the getUserPreferences() function.

Get hands-on with 1400+ tech skills courses.