我的代码加载了一个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
}

问题是加载事件处理程序没有运行.

有人能帮我吗?

推荐答案

问题是,如果延迟设置事件处理程序直到加载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属性;details.)

在您的用例中,等待load事件确实是有意义的,因此您必须等待load andfetch都完成:

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
}

旁注:注意我在打json之前加了一张ok的支票.fetch只在network个错误上拒绝promise ,而不是HTTP错误.这是我在旧的贫血博客here上报道的fetch API中的一个例子.

Javascript相关问答推荐

我可以使用CSS有效地实现最大宽度=100%和最大高度=100%,而无需父母有明确的/固定的宽度和高度,替代方法吗?

react/redux中的formData在expressjs中返回未定义的req.params.id

判断表格单元格中是否存在文本框

单击ImageListItemBar的IconButton后,在Material—UI对话框中显示图像

如何从Intl.DateTimeFormat中仅获取时区名称?

XSLT处理器未运行

Angular 中的类型错误上不存在获取属性

S文本内容和值不必要的不同

使用Google API无法进行Web抓取

try 使用javascript隐藏下拉 Select

使用Nuxt Apollo在Piniastore 中获取产品细节

自定义图表工具提示以仅显示Y值

令牌JWT未过期

如何通过Axios在GraphQL查询中发送数组

重新呈现-react -筛选数据过多

无法使用Redux异步函数读取未定义的useEffect钩子的属性';map';

如何为两条动态路由创建一个页面?

MUI-TABLE:MUI表组件中交替行的不同 colored颜色 不起作用

Node.js的Fetch()调用总是创建新的Express会话

鼠标进入,每秒将图像大小减小5%