How to deal with multiple async requests in JavaScript

Introduction

In this post, I will show you how to send multiple requests in JavaScript correctly.

Sequential way to send requests

The most popular way of sending fetch requests is sending them sequentially (await line by line). But in JavaScript, we can also them in parallel. When data is fetched sequentially your requests look like the example below:

const products = await getProducts();
const comments = await getComments();

But with this type of sending the request there is a flaw. If you look at the network tab in your dev tools you will notice that the second request waits for the first to be completed. Which is not the best situation for us.

Solution: send requests in parallel

If data sets aren't interdependent you can call fetching functions and then await the Promise.

const productsPromise = getProducts();
const commentsPromise = getComments();

const products = await productsPromise;
const comments = await commentsPromise

You can also use the Promise.all() function which is a more elegant way to handle multiple promises. Promise.all() returns an array of results so you can destructure it.

const [products, comments] = await Promise.all([getProducts(), getComments()])

This method improves the performance and load time of your app by up to 60%.

Caveats

As I mentioned before you can send requests in parallel if data sets don't depend on one another. When posts have reactions that you have to fetch you must await getPosts() before you send requests for reactions. But remember the posts and comments don't depend on themselves so you can send requests together initially to save time.