【问题标题】:How to combine a loop of Axios calls with an await-ed function?如何将 Axios 调用循环与等待函数结合起来?
【发布时间】:2019-11-08 05:32:30
【问题描述】:

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

问题:在当前版本中,主游戏循环(在“一旦验证清除,游戏在下面开始” 评论之后开始)必须在验证之后开始,而实际上它是同时开始,这把一切都搞砸了。

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

有什么办法摆脱这个烂摊子吗?

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

【问题讨论】:

    标签: vue.js async-await axios


    【解决方案1】:

    execute 中使用await 并返回真/假,然后使用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();

    【讨论】:

      猜你喜欢
      • 2017-04-08
      • 1970-01-01
      • 2021-12-22
      • 2012-09-16
      • 1970-01-01
      • 2020-04-12
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多