在等待异步功能后,不调用onload事件侦听器

发布于 2025-01-24 00:59:03 字数 550 浏览 2 评论 0原文

我的代码加载了一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月野兔 2025-01-31 00:59:03

问题在于,通过延迟设置事件处理程序直到加载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
}

如果您确保您的脚本标签使用type> type =“ module”(如果您使用的是Top级等待这样),则必须这样做),它将在页面html满载并构建DOM之前运行。 (除非您还在其上具有async属性; 详细信息。)

在您的用例中,等待load事件确实很有意义,因此您必须等到两个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提取仅拒绝其在网络上的承诺错误,而不是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:

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
}

If you make sure your script tag uses type="module" (which yours must do, if you're using top-level await like that), it won't be run until the page HTML is fully loaded and the DOM has been built. (Unless you also have the async attribute on it; details.)

In your use case, waiting for the load event genuinely does make sense, so you'll have to wait until both load and the fetch are done:

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
}

Side note: Notice I added a check for ok before calling json. fetch only rejects its promise on network errors, not HTTP errors. This is (IMHO) a footgun in the fetch API I cover on my old anemic blog here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文