Proper syntax for arrow functions; async; await; promise

As an amateur I make small games. One of them works properly with all fashioned call to functions and I’m trying to rewrite it in todays Javascript. I came up with this:

const loadingGame = async function() {
        return new Promise((resolve, reject) => {
            let y = 0
            setTimeout(() => {
                for (i = 0; i < 10; i++) {
                    y++
                }
                console.log('Loading game completed.')
                resolve(y)
            }, 10000)
        })
    }


    const checkTurn = async function() {
        setTimeout(function() {
            if (polling === false) {
                console.log("It's my turn to play so I no need to check that...");
                return;
            }
            console.log('Checking if it"s my turn to play');
            $.post(
                'checkTurn.php', {
                    gameId: gameId,
                    friendly_gameDB: friendly_gameDB,
                    Username: denBrukeren,
                },
                function(data, status) {
                    myObj = JSON.parse(data);
                    turnPlay = myObj[0]['turnPlay'];
                }
            );
            if (turnPlay === friendly.name) {
                polling = false;
                friendly.isMyTurn = true;
                const result = await loadingGame();
            }
            console.log('Check if it is my turn to play again after 5 sec.');
            checkTurn();
        }, 5000);
    }

    checkTurn();

From what I read it seems ok? But I get an error with that line:

const result = await loadingGame();

The error being: await is only valid in async functions and the top level bodies of modules

Please be patient and try to explain me like you are talking to a 5 years old. :grinning: My head is quite spinning since yesterday I try to make sense in the syntax of those ‘new’ things.

Thanks for help.

Hi,

As you’re probably aware, the await keyword is used in JavaScript to wait for an asynchronous operation (e.g. a function that takes some time to complete) to finish. But await can only be used inside functions that are marked as async.

The error in your code is because you’re using await inside the setTimeout callback within the checkTurn function. However, the callback function itself is not marked as async.

To fix this, you need to make the callback function inside setTimeout an async function.

const checkTurn = async function() {
  setTimeout(async function() { // <--- Mark this function as async
    / ... rest of your code ...
    if (turnPlay === friendly.name) {
      polling = false;
      friendly.isMyTurn = true;
      const result = await loadingGame();
    }
    // ... rest of your code ...
  }, 5000);
}

checkTurn();

Does that make sense?

If you’d like to read more about this, this article might help.

1 Like

Hi;

Ooookayyyy… I had tried:

async setTimeout(function(){},5000)

Gonna do the change.

Thanks. :+1:

Yep; works fine!!!

Thanks again. :slightly_smiling_face:

1 Like