Adam James

Jun 28, 2021

2 min read

Async/Await in JavaScript Fetch Requests

While going through Flatiron School’s bootcamp, one concept that came up over and over again (as it should, it’s an important concept!) was the use of asynchronous actions and fetch requests. Fetch requests allow you to make network requests through the use of Promises. Through the bootcamp, we learned how to make fetch requests by chaining .then methods to handle the promise that’s returned by the request. However, after finishing I found an alternative to the .then chain that makes the entire request more readable. By using the async and await keywords, you can avoid using .then methods entirely and make the entire process easier to comprehend for anybody reading your code!

In this blog post, I’ll break down the differences between a fetch request that uses async/await and one that doesn’t through a fetch request that I used in a React Native project I started to build after finishing at Flatiron School.

fetchReviews from my React Native application

Here’s the fetch request I used to populate my application with data from my account with Google’s Firebase database (sponsor me Google). The first difference from a fetch request without async/await is placing the keyword “async” at the return function. Using async makes a guarantee that the return value of the function will be a promise.

Inside the async function, you’ll want to set a variable to the fetch request but using the await operator before the request begins. The await operator is used to wait for a promise from an async function. If a promise is passed to await, it’ll wait for the promise to be fulfilled then do something with that fulfilled value. In my example, I use await twice. First, at the initial fetch request. After that promise is fulfilled, we set another variable that awaits the json fetched from the response promise. Once that responseData is available, I was able to dispatch that to my application’s state through React-Redux and Thunk.

So there you have it! This isn’t a very in-depth blog post because there aren’t many differences outside of syntactic changes between the two concepts. While there isn’t a gigantic difference in efficiency between the two methods, you should always strive to maintain more readable code for anybody who is either working on your legacy project or reading through your code for any other reason. Next time you start developing an application that requires any form of fetch request, you should consider using async/await.