drake035
drake035

Reputation: 2887

How to combine a loop of Axios calls with an await-ed function?

That's a tricky one I guess. I'm prompting user for a word which I validate with an Axios API call. Once validation clears, the main loop of my game - hangman - starts with a wait between each move (hence the use of await).

Problem: in current version, the main game loop (starting after "once validation clears, game starts below" comment) must starts after validation, when in fact it starts at the same time which messes everything up.

And I can't put my main loop inside the then() part of my Axios call because in that case the await-ed function call ceases to work.

Any idea to get out of this mess?

    async startGameComputerGuesser () {
      var wordIsValidated = false
      const vm = this
      const dispatcher = {
        execute: function () {
          const wordApiBaseUrl = 'https://www.dictionaryapi.com/api/v1/references/sd4/xml'
          wordToGuess = prompt('Enter a word:').toLowerCase()
          const dispatcher = this
          vm.axios.get(`${wordApiBaseUrl}/${wordToGuess}?key=${wordApiKey}`).then(res => {
            if (!res.data.includes('def')) {
              dispatcher.execute()
            } else {
              wordIsValidated = true
            }
          })
        }
      }
      dispatcher.execute()

      // once validation clears, game starts below
      if (wordIsValidated) {
        while (!this.$store.state.gameIsOver) {
          await this.resolveAfter2Seconds()
          // main loop of the game goes here
        }
      }
    }

Upvotes: 2

Views: 137

Answers (1)

Ja9ad335h
Ja9ad335h

Reputation: 5075

use await inside the execute and return true/false then use while to check that condition like below

async startGameComputerGuesser() {
  let wordIsValidated = false;
  const vm = this;
  const dispatcher = {
    async execute() {
      const wordApiBaseUrl = 'https://www.dictionaryapi.com/api/v1/references/sd4/xml'
      const wordToGuess = prompt('Enter a word:').toLowerCase();
      const res = await vm.axios.get(`${wordApiBaseUrl}/${wordToGuess}?key=${wordApiKey}`);
      return res.data.includes('def');
    }
  }

  // validation
  while (!wordIsValidated) {
    wordIsValidated = await dispatcher.execute();
  }

  // game starts below
  while (!this.$store.state.gameIsOver) {
    await this.resolveAfter2Seconds()
    // main loop of the game goes here
  }
} 

Example code:

const startGameComputerGuesser = async function() {
  let wordIsValidated = false;
  
  const dispatcher = {
    async execute() {
      const res = await new Promise(res => setTimeout(() => res(Math.floor(Math.random() * 10)), 500));
      console.log(res);
      return res == 6;
    }
  }

  // validation
  while (!wordIsValidated) {
    wordIsValidated = await dispatcher.execute();
  }
  
  // once validation clears, game starts below
  console.log('started');
}

startGameComputerGuesser();

Upvotes: 2

Related Questions