在等待异步功能后,不调用onload事件侦听器
我的代码加载了一个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
}
问题是负载事件处理程序未运行。
有人可以帮我吗?
My code loads a JSON file that is later used in a function called serverTest
.
So I have this code:
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
}
The problem is that the load event handler does not run.
Can someone help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于,通过延迟设置事件处理程序直到加载JSON,您就缺少
load
事件。在绝大多数用例中(但是来自评论,而不是您的评论),只需完全删除事件处理程序:
如果您确保您的
脚本
标签使用type> type =“ module”
(如果您使用的是Top级等待
这样),则必须这样做),它将在页面html满载并构建DOM之前运行。 (除非您还在其上具有async
属性; 详细信息。)在您的用例中,等待
load
事件确实很有意义,因此您必须等到两个load> load
> 和完成了fetch
:附带注意:注意我在调用
ok
之前添加了检查json
。提取
仅拒绝其在网络上的承诺错误,而不是http错误。这是(IMHO)fetch
api i在我旧的贫血博客上覆盖的脚步在这里。The problem is that by delaying setting up the event handler until the JSON is loaded, you're missing the
load
event.In the vast majority of use cases (but from the comments, not yours), just remove the event handler entirely:
If you make sure your
script
tag usestype="module"
(which yours must do, if you're using top-levelawait
like that), it won't be run until the page HTML is fully loaded and the DOM has been built. (Unless you also have theasync
attribute on it; details.)In your use case, waiting for the
load
event genuinely does make sense, so you'll have to wait until bothload
and thefetch
are done:Side note: Notice I added a check for
ok
before callingjson
.fetch
only rejects its promise on network errors, not HTTP errors. This is (IMHO) a footgun in thefetch
API I cover on my old anemic blog here.