0
async function players_online() {
    const response = await fetch("http://ip:port/dynamic.json");
    const data = await response.json();
    console.log(data.clients);

    }

我可以在其他函数中使用数据吗?示例:

async function players() {
console.log(data.clients);
}

当我这样做时,我会收到未定义的

4

1 回答 1

1

“是的你可以:

let data 

async function players_online() {
    const response = await fetch("http://ip:port/dynamic.json");
    data = await response.json();
}

async function players() {
    // You can't ensure data is already set!!!
    console.log(data.clients);
}

但是,您不能确保此时已经定义了数据。您必须通过自己的代码确保players_online在调用之前调用并等待players

您可以通过如下调用订单来确保这一点:

async function players_online() {
    const response = await fetch("http://ip:port/dynamic.json");
    const data = await response.json();
    await players(data)
}

async function players(data) {
    console.log(data.clients);
}
于 2022-01-07T00:09:11.597 回答