Improving Code Readability With Async/Await

Last updated 3 years ago by Ben McCormick


When it first became a part of JavaScript, I wasn’t sure how much I was going to use async-await. I could see that it made things prettier in some cases, but I was pretty happy with my promise chains and thought that async-await might just be some extra language baggage. Since then I’ve fully converted; it’s one of my favorite features added to the language in recent years. The reason? It helps you write code in a linear manner.

A principle of readable code:

Code should where possible be written in the order in which a reader needs to understand it.1

For complex classes, this ideally means that the “entry points” are towards the top, with the helper methods below to be read as needed1. But for “linear” code that reflects a workflow, we want the code to progress in chronological order as much as possible. With imperative code that tends to happen by default. But JavaScript’s asynchronous constructs have tended to obscure chronological orders.

As an example, here is a React component that displays the time remaining in a user session based off of some cookie values. It checks a cookie on a regular interval to see whether it should display a warning about the session timeout. Once it is showing the warning, it begins checking the cookie more frequently in order to show a timeout. Once the session expires, it can stop checking.

Read full Article