我的代碼加載了一個 JSON 檔案,該檔案稍后用于名為serverTest
.
所以我有這個代碼:
async function fetchJSON(url) {
const response = await fetch(url, {
headers: { accept: "application/json" }
});
return response.json();
}
const config = await fetchJSON("./config.json");
window.addEventListener("load", function() {
serverTest(0);
});
const serverList = new Map(Object.entries(config.servers));
function serverTest(index) {
// code including serverList
}
問題是加載事件處理程式沒有運行。
有人能幫我嗎?
uj5u.com熱心網友回復:
問題是通過延遲設定事件處理程式直到 JSON 被加載,你錯過了load
事件。
在絕大多數用例中(但來自評論,而不是您的),只需完全洗掉事件處理程式:
async function fetchJSON (url) {
const response = await fetch(url, {
headers: { accept: "application/json" }
});
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
return response.json();
}
const config = await fetchJSON("./config.json");
serverTest(0); // <==== Not wrapped in a `load` event handler
const serverList = new Map(Object.entries(config.servers));
function serverTest(index) {
//Code including serverList
}
如果您確保您的script
標簽使用type="module"
(您必須這樣做,如果您使用的是這樣的頂級標簽await
),它不會運行,直到頁面 HTML 完全加載并且 DOM 已經構建。(除非你也有async
它的屬性;詳細資訊。)
在您的用例中,等待load
事件確實有意義,因此您必須等到兩者load
都完成fetch
:
async function fetchJSON (url) {
const response = await fetch(url, {
headers: { accept: "application/json" }
});
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
return response.json();
}
// Hook up the `load` event *before* loading `config.json`,
// get a promise for when it fires
const loadPromise = new Promise(resolve => {
window.addEventListener("load", resolve);
});
// Load and wait for `config.json`
const config = await fetchJSON("./config.json");
// Wait for the `load` event (waits only ***very*** briefly
// if the event has already fired, otherwise waits for it
// to fire)
await loadPromise();
serverTest(0);
const serverList = new Map(Object.entries(config.servers));
function serverTest(index) {
//Code including serverList
}
旁注:請注意,我ok
在呼叫json
. fetch
只拒絕它對網路錯誤的承諾,而不是 HTTP 錯誤。這是(恕我直言)fetch
我在我的舊博客上介紹的 API中的一支槍。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/469323.html
標籤:javascript 异步 异步等待 负载
上一篇:AngularonElectron-使用Observable更新UI
下一篇:如何在C#中異步搜索按鍵