0

Hi I would like to store players and currentPlayer as global variables, however the function that returns the result I need is async. Is there a way to set these as global variables?

let message = document.getElementById('game-message');
// async allows the use of the "await" keyword
async function setPlayers() {
    message.innerHTML = `<p>Name of player One?</p>`;
    let player1 = await getUserInput();
    message.innerHTML = `<p>Name of player Two</p>`;
    let player2 = await getUserInput();
    const players = [];
    players.push(player1, player2);
    return players;
}

var currentPlayer = players[0];
const players = (async () => {
    const players = await setPlayers();
    return players;
})();

This is what i have but i also need setPlayers to run!

NovaBrownie
  • 117
  • 6
  • You can assign global variables in an async function. The new values won't be available immediately after you call, but they'll be available if you try to use them from later event listeners. – Barmar May 03 '23 at 20:19
  • See also https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – Jared Smith May 03 '23 at 20:19
  • 1
    You can set a global value inside an async function just fine. The issue is that there's no *(default)* mechanism for "outside" code to know when the value is valid. – Dave Newton May 03 '23 at 20:19
  • You can only have the list of players when the user has input them, so you cannot expect your **synchronous** executing code (like `const players = `) to get a result **now**, when that result will only become available in some **future**. So instead of `return players`, do all that you need to do with `players` inside that async function, or make function calls from there. – trincot May 03 '23 at 20:20

0 Answers0