I actually consume some remote API using the FETCH API like below
document.addEventListener("DOMContentLoaded", () => {
loadCart();
aggregateSearch("france", ["api1", "api2"]);
});
const aggregateSearch = async (term, AvailableApis) => {
console.log("aggregateSearch")
await Promise.all(AvailableApis.map((api) => {
fetchApi(api, term);
}))
};
const fetchApi = async (api, term) => {
console.log("fetchApi");
const aggregateRawResponse = await fetch('aggregate.php', { method: 'POST', body: JSON.stringify({ source: api, term: term }) });
const aggregateResponse = await aggregateRawResponse.json();
console.log('response from API done');
document.getElementById('myDiv' + api)?.innerHTML = aggregateResponse.formattedResponse;
}
const updateCartCount = async () => {
console.log("update cartcount"); // this line is executed
const fetchNbPhotos = await fetch("count.php");
const data = await fetchNbPhotos.json();
console.log("cart count done");
document.getElementById('cartCounter').innerHTML = parseInt(data["nb"]); // this is executed once aggregateSearch done
}
const loadCart = () => {
console.log("start loading cart");
fetch('cart.php')
.then((response) => {
return response.text();
})
.then((html) => {
console.log("loading cart is done updating cart count");
document.getElementById('cart')?.innerHTML = html
updateCartCount();
});
}
Here the console output
start loading cart
aggregateSearch
fetchApi
loading cart is done updating cart count
update cartcount
cart count done
response from API done
The part that retrieves the contents of the APIs works perfectly, but the part that load my cart into cart
div and updating my cartCounter
div is only update once aggregateSearch
has finished.
I tried to make loadCart async/await but without success
How can I make aggregateSearch
non-blocking and update my cartCounter
div while fetching API is pending ?