Using Async/Await When Chaining Fetch Requests in JavaScript

Photo by Kai Pilger on Unsplash

For my latest project, I wanted to create the ability to favorite and unfavorite a breathing technique. When I first decided to tackle this in React, I thought I could create two separate callback functions to pass into my onClick handler (favoriteBT() and unfavoriteBT()). However, I later realized that I could use if/else statements to toggle the favoriting functionality. So, I decided to use one function to handle both: toggleFavBT().

The Problem

I would need to chain two fetch requests, and the second one would depend on the data returned from the first. However, since fetch requests are asynchronous, the second fetch request would fail because it would not receive data from the first fetch in time. In other words, the second request continues to execute without waiting for the first fetch to finish.

If you take a look below, you’ll see that I use setState to update the state for the favorite object. However, the second fetch request, which uses a PATCH, depends on the favorite object’s id. Unfortunately, because of asynchronous JavaScript, the first request doesn’t finish before the second. So, the PATCH request is not able to complete. The fav_id key is never assigned.

The Solution

Fortunately, JavaScript offers the async and await feature, which helps us mimic synchronicity. When you use the async keyword with a fetch request, that indicates that the async function will stop executing the rest of the code until the promise is resolved. Take a look below, where I label the async function toggleFavBT() and precede each fetch request with await keywords:

That means that the second fetch request waits for the first promise to resolve, so it updates state for the favorite object. Then, the second fetch is able to successfully update the fav_id for the breathing technique. That’s because when the first fetch’s promise is resolved, the JavaScript engine can continue to execute the code. However, instead of resulting in a promise, it returns parsed JSON data.


Full Stack Software Engineer open to work. Experience in JavaScript, React.js, and Ruby on Rails.