我实际上使用 FETCH API 来使用一些远程 API,如下所示
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();
});
}
这里是控制台输出
start loading cart
aggregateSearch
fetchApi
loading cart is done updating cart count
update cartcount
cart count done
response from API done
检索 API 内容的部分工作完美,但将我的购物车加载到
cart
div 并更新我的 cartCounter
div 的部分仅在 aggregateSearch
完成后更新。
我尝试使 loadCart 异步/等待,但没有成功
如何在获取 API 挂起时使
aggregateSearch
非阻塞并更新我的 cartCounter
div?
这里的await关键字暂停执行,直到promise完成。如果您不希望它被阻塞,我建议不要使用 async/await。