Axios requests are Promise based and are by default awaited. That means, that if we need to make two API requests from the same place, we need to wait for the response of the first request before making the second request.
However, we can make all the requests we want at once using Promise.all() method. This method will wait until the last API request is finished and then only return its control.
Consider we want to make GET API requests to the following URLs at once:
Let’s have a look at how we can make requests. Here’s my axios.js file containing just the getData method to handle GET requests:
And here’s the file from which we’ll make the concurrent API requests:
In the file above, we’ve first created a list of URLs using a for-loop. We’ve then passed in the URLs list to Promise.all(). You’d notice that we’ve create an async method makeRequests. This is to ensure that we can await the Promise response. Again in the promise callback method for each of the URL, we’ve made it async (line 10) so that we can await the getData method.