Making Fetches Easy With Async Await

Mickey Sheridan
3 min readMay 9, 2019

--

Asynchronous requests are the source of many common and frustrating bugs in otherwise clean code. Because most of programming involves the application of pure, sequential code, the concept of concurrency alone can often disorient a programmer’s flow — and create unnecessary debugging time.

Remember: Helm’s Deep was saved only through the implementation of clear and reliable asynchronous processes. Sometimes proper fetch calls can really mean life or death.

Because of the frustrating nature of asynchronous calls, JavaScript has made many helpful quality-of-life improvements on how these things were handled. The introduction of Promise , fetch , and .then() cleaned up the endless nested callbacks required for complicated XMLHttpRequests . But fetch calls are not without their own considerable issues. As the request gets more detailed, chaining .then callbacks can get messy:

Chains such as this are bugs waiting to happen. There are certainly best practices for keeping long requests organized. But overall, .then() can be a headache.

ES7 brought about a new way to solve these structural issues with the introduction of two new key words: async and await . Let’s see it in action, consider this fetch call:

The call makes a request to the Star Wars API. Once the request is fulfilled, the promise is processed into a JavaScript object, and then logged.

Here’s the same function refactored into an async function. We declare async functions by using the key word in combination with the function declaration. Now we can assign the resolved value of the fetch call to a variable and use it anywhere within the method scope!

What await is doing is halting the progression of the method until the fetch promise resolves. This way, we can more directly and intuitively control the flow of asynchronous calls.

Don’t let the syntax coloring fool you: chrome understands these awaits, even if my editor doesn’t…

Here we initiate each Promise at the start of the function, and then execute their executions in the order desired. Even though we have three asynchronous requests, we can resolve them in an exact order using await .

This is all achievable with .then() . Really, await is mostly syntactic sugar. But, it allows you to execute tricky asynchronous sequences without the same headaches.

Here, we’re not only retrieving, but also actively processing information in a fashion which closely resembles sequential code. That’s because it pretty much is sequential code at this point! All we need to think about is what we need to await and when we need to await it.

A final example. How will these two execute differently? Which one would probably be faster? See how await allows clear and effective control over the flow of your promises. This is sure to make your asynchronous calls far less messy, and your life slightly more bug-free!

--

--