javascriptdiscord.jsfivem

Can I use variables that are inside functions outside them?


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

    }

Can i use data inside other function? Exemple:

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

When i do this i recive undefined


Solution

  • "Yes", you can:

    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);
    }
    

    However you can not ensure that data is already defined at that point. You have to ensure by your own code that players_online is called and awaited before you call players.

    You can ensure this with a call order like that:

    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);
    }