Home > Software design >  Can I use variables that are inside functions outside them?
Can I use variables that are inside functions outside them?

Time:01-07

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

CodePudding user response:

"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 the call order with 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);
}
  •  Tags:  
  • Related