[英]javascript: Update the DOM only when the result is ready
我有一些 api 端點。
一個返回所有服務器詳細信息( https://dnscheck.io/api/serverDetails/ )其他是server specific
端點。 ( https://dnscheck.io/api/query/?id=2&type=A&hostname=test.com )對於每個 server_Id (我從serverDetails
端點獲得),我必須調用每個 Z8A5DA55EAZ70ED12657447D
我所做的是。
我遍歷結果數組(我從serverDetails
端點獲得)
對於循環的每次迭代,我調用每個端點來獲取 ip。
環形:
for (const [index, item] of data.entries()) {
const res = await fetch(
`https://dnscheck.io/api/query/?id=${item.id}&type=${query.type}&hostname=${query.host}`
);
const result = await res.json();
renderResult(result, item, index);
}
渲染功能:
const renderResult = (result, data, index) => {
const ip = document.querySelector(`.ip-address${index + 1}`);
ip.innerHTML = result.answers[0].address;
};
這樣,結果就會以同步的方式顯示在 DOM 中。 (相繼)
但是,我想要的是,一旦結果准備好,就用結果更新 dom。
我能做些什么?
不要使用await
,因為它會阻塞for
循環並對結果進行排序。 使用.then()
代替。
for (const [index, item] of data.entries()) {
fetch(
`https://dnscheck.io/api/query/?id=${item.id}&type=${query.type}&hostname=${query.host}`
).then(res => res.json())
.then(result => renderResult(result, item, index));
}
您可以通過在陣列上使用map
並在其中使用fetch
來並行執行它們。 您可以通過使用Promise.all
來觀察它們的整體結果,以了解它們何時全部完成:
await Promise.all(
data.entries().map(async (index, item) => {
const res = await fetch(
`https://dnscheck.io/api/query/?id=${item.id}&type=${query.type}&hostname=${query.host}`
);
// You need to check `res.ok` here
const result = await res.json();
renderResult(result, item, index);
)
);
請注意,如果任何輸入承諾拒絕, Promise.all
將立即拒絕其 promise。 如果您想知道什么成功和什么失敗,請改用allSettled
:
const results = await Promise.allSettled(
data.entries().map(async (index, item) => {
const res = await fetch(
`https://dnscheck.io/api/query/?id=${item.id}&type=${query.type}&hostname=${query.host}`
);
// You need to check `res.ok` here
const result = await res.json();
renderResult(result, item, index);
)
);
// Use `results` here, it's an array of objects, each of which is either:
// {status: "fulfilled", value: <the fulfillment value>}
// or
// {status: "rejected", reason: <the rejection reason>}
關於我的“您需要在此處檢查res.ok
”注意:不幸的是,這是fetch
API 中的一支手槍。 它僅在網絡故障時拒絕其 promise,而不是 HTTP 錯誤。 所以404
導致 promise 完成。 我 在這里寫一下。 通常最好的辦法是讓你調用包裝函數,例如:
function fetchJSON(...args) {
return fetch(...args)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`); // Or an error subclass
}
return response.json();
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.