Home > Back-end >  Force node to wait for input before proceeding?
Force node to wait for input before proceeding?

Time:12-31

I am making a turn based game using node as my server side code. The problem is I have no clue how to make the program wait for input before going onto another function. Preferably, I'd like it to wait for player 1's action, and once recieved, then wait for the next player until all turns are done. Also, this just executes nextFunction immediately which makes sense after learning about asynchronous execution, but this is a case where I don't want that to happen.

    this._players.forEach((player, idx) => {
      player.on('turn', (turn) => {
        this._turns[index] = turn;
      });
    });
    nextFunction();

I attempted to use async, await, and also promises but I don't think I implemented them properly. I'm also not sure that .on() is even the way to go. On my client side, for reference, I have a few buttons that when pressed, emit an id which I can use server side to do logic on. I think .then() might help but it might make the code difficult to maintain and also keep track of while developing due to the amount of .then()'s I'll probably need to use. Is there a better way to code this in node?

Basically, I need my code to wait for user input before moving on.

CodePudding user response:

        async function getAction(index, playerArray) {
            var turn = null;
          let myPromise = new Promise(function(resolve) {
                playerArray[index].id.on('turn', (turn) => {
                resolve(turn);
                })
          });
          turn = await myPromise;
          return(turn);
        }

        async function getAmount(index, playerArray) {
            var amount = null;
          let myPromise = new Promise(function(resolve) {
                playerArray[index].id.on('amount', (amount) => {
                resolve(amount);
                })
          });
          amount = await myPromise;
          return(amount);
        }

Pretty sure that works, just tested now. Surely there is a more concise way of achieving the same thing but it works.

CodePudding user response:

You can use once to create a promise that waits for a single event. Then use that in your loop:

for (const [index, player] of this._players.entries()) {
  this._turns[index] = await once(player, 'turn');
}
nextFunction();
  • Related