如何将Axios调用循环与等待功能结合在一起?

我猜那是一个棘手的问题。我正在提示用户输入一个用Axios API调用验证的单词。验证清除后,我的游戏“ hangman”的主循环开始于每次移动之间的等待(因此使用await)。

问题:在当前版本中,主游戏循环(在“一次验证清除后开始,游戏从下面开始” 注释后开始)必须在 验证后开始,实际上同时开始,这一切都搞砸了。

而且我无法将主循环放在then()调用的Axios部分内,因为在这种情况下,等待的函数调用停止工作。

有摆脱这种混乱的想法吗?

    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
        }
      }
    }
wwwqq20010 回答:如何将Axios调用循环与等待功能结合在一起?

await中使用execute并返回true / false,然后使用while来检查这种情况,如下所示

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
  }
} 

示例代码:

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();

本文链接:https://www.f2er.com/3141825.html

大家都在问