Search code examples
javascriptfunctionasynchronouspromisees6-promise

How to wait for promises to be resolved


I have created a function verifyIfUserIsInGame(userId) that allows checking if the user given as argument is in game. This function searches the Firebase database and returns true or false. (so it is a promise within the function).

I would now like to check, once the function has been executed for 2 users if they are in play. I'm not very comfortable with promises. I made this code but it doesn't work since I get [object Promise] in the console logs.

  // We check that both users are in this game
  user1IsInGame = verifyIfUserIsInGame(user1Id); // must return true or false
  user2IsInGame = verifyIfUserIsInGame(user2Id); // must return true or false

  console.log("user1: " + user1IsInGame);
  console.log("user2: " + user2IsInGame);

  if (userIsInGame && user2IsInGame) {
    // The users are in game
  } else {
    // The users are not in game
  }
});

Thanks for your help.


Solution

  • As already mentioned, you can use Promise.all, but none of the other answers had any content in your verify function, so just wanted to provide a full example.

    This is one way of doing it, you can ofc change the resolve to just pass true/false back and then change the if statements.

    function verifyIfUserIsInGame(user_id) {
      return new Promise((resolve, reject) => {
        resolve({ id: user_id, inGame: true });
      });
    }
    
    // run this when all checks have been performed.
    function callbackFunction(players){
    
      let playersReady = 0;
      players.forEach(player => {
        if(player.inGame){
          console.log(`player ${player.id} are in the game`);
          playersReady++;
        }
      });
      if(playersReady === players.length){
        console.log("All players are in the game");
      }
      
    }
    
    
    // the checks we want to perform
    const verifyAllUsers = [
      verifyIfUserIsInGame(1),
      verifyIfUserIsInGame(2)
    ];
    
    // wait for promises to finish.
    Promise.all(verifyAllUsers)
           .then( users => callbackFunction(users) )
           .catch( err => console.error(err) );