Axios - Merge Multiple HTTP GET Requests To A Single Array
by sbhomra
HTML
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.3.4/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsrender/1.0.12/jsrender.min.js"></script>
<div id="result"></div>
<script id="js-product-template" type="text/x-jsrender">
<img src={{:thumbnail}} width="150" />
<br />
<br />
<strong>Title:</strong> {{:title}}
<br />
<strong>Description:</strong> {{:description}}
<br />
<strong>Category:</strong> {{:category}}
<br />
<br />
<hr />
</script>
JavaScript
// 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);
});