Let's assume that we want to simulate the behaviour of a dice, returning a random value between [1, 6] after 3 seconds:
javascriptconst rollDice = () => { let random = new Promise(resolve => { setTimeout(() => resolve(Math.floor(Math.random() * 6) + 1), 3000); }); return random; }
Now, two players join the game: who rolls the dice and gets a higher value, wins (yes, so an exciting game 😅).
javascriptconst game = async () => { // Player one rolls the dice // Waits 3 seconds let player_1 = await rollDice(); console.log(player_1); // Now, it's turn to player two // Waits 3 seconds as well let player_2 = await rollDice(); console.log(player_2); // Printing the results if(player_1 > player_2) console.log('Player 1 won'); if(player_1 < player_2) console.log('Player 2 won'); if(player_1 === player_2) console.log('Draw'); }
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.