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:
https://www.api.example.com/user/0
https://www.api.example.com/user/1
https://www.api.example.com/user/2
https://www.api.example.com/user/3
https://www.api.example.com/user/4
https://www.api.example.com/user/5
https://www.api.example.com/user/6
Code language: JavaScript (javascript)
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:
import axios from 'axios'
const getRequestHeaders = () => {
if (getAuthorizationToken()) {
headers: {
'Authorization': `Bearer ${getBearerToken(BEARER_TKN)}`
},
}
else
return null;
}
const getData = async (url: string) => {
await axios.get(url, getRequestHeaders())
.then(function (response) {
if (response !== null) {
return response
}
})
.catch(function (error) {
if (error.response) {
// handle response error
} else if (error.request) {
// handle request error
} else {
// handle network error
}
});
}
Code language: JavaScript (javascript)
And here’s the file from which we’ll make the concurrent API requests:
const makeRequests = async () => {
const urlString = 'https://www.api.example.com/user'
const urlPaths = []
for (let i = 0; i< 10; i++) {
const path = `${urlString}/i`
urlPaths.push(path)
}
await Promise.all(urlPaths.map(async (urlPath) => {
const result = await getData(urlPath, true);
if (result != null && 'data' in result) {
if (result.data != null) {
// handle response data
}
}
}));
}
makeRequests()
Code language: JavaScript (javascript)
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.