There are times when you need to call multiple API endpoints to return different data based on the same data structure. Normally, I'd go down the approach of manually creating multiple Axios GET requests and then inserting the endpoint responses into a single object array. But there is a more concise and readable way to handle such tasks.
With the help of DummyJson.com, we will be using the product search endpoint to search for different products to consolidate into a single array of product objects: /products/search?q=
.
As you can see from the code below, we start off by populating an array with a list of API endpoints where multiple GET request can be carried out for each endpoint from our array. The requests
variable contains an array of promises based on each of these GET requests.
Finally, axios.all()
allows us to to make multiple HTTP requests to our endpoints altogether. This function can only iterate through a collection of promises. For more information regarding this Axios function, I found the following article very insightful for a better understanding: Using axios.all to make concurrent requests.
// List all endpoints.
let endpoints = [
'https://dummyjson.com/products/search?q=Laptop',
'https://dummyjson.com/products/search?q=phone',
];
// Perform a GET request on all endpoints.
const requests = endpoints.map((url) => axios.get(url));
// Loop through the requests and output the data.
axios.all(requests).then((responses) => {
let data = [];
responses.forEach((resp) => {
data.push(...resp.data.products)
});
// Output consolidated array to the page.
const template = $.templates("#js-product-template");
const htmlOutput = template.render(data);
$("#result").html(htmlOutput);
});
As we're looping through each request, we push the response to our data
array. It is here where we merge all requests together into a single array of objects. To make things a little more easier to display the results to the page, I use the jsrender.js templating plugin.
A working demo can be seen on JsFiddle.