【问题标题】:How to exit a while loop depending of the result of an Axios call?如何根据 Axios 调用的结果退出 while 循环?
【发布时间】:2020-03-04 09:42:29
【问题描述】:

为了确保存在用户输入的单词,我需要不断提示(while 循环)输入单词,直到单词 API 找到该单词。

我的问题是:如何根据 Axios 调用结果退出 while 循环?

下面是我目前的代码。

const wordApiBaseUrl = 'https://www.dictionaryapi.com/api/v1/references/sd4/xml'
while (true) {
  const wordToGuess = prompt('Enter a word:').toLowerCase()
  const endPointUrl = `${wordApiBaseUrl}/${wordToGuess}?key=${wordApiKey}`
  this.axios.get(endPointUrl).then(res => {
    if (res.data.includes('def')) {
      break
    }
  })
}

【问题讨论】:

    标签: vue.js while-loop axios


    【解决方案1】:

    试试这个:

    const wordApiBaseUrl = 'https://www.dictionaryapi.com/api/v1/references/sd4/xml'
    
    const vm = this; // <--- assuming this is the Vue instance
    const dispatcher = {
    
        execute: function() {
            const wordToGuess = prompt('Enter a word:').toLowerCase()
            const endPointUrl = `${wordApiBaseUrl}/${wordToGuess}?key=${wordApiKey}`
            const dispatcher = this;
            vm.axios.get(endPointUrl).then(res => {
    
                if (!res.data.includes('def')) {
                    dispatcher.execute();
                }
            })
        }
    }
    dispatcher.execute();
    

    您可以在我们的 Promise 中使用递归,而不是使用 while 循环或 async/await。如果结果不满意,请重新运行 AJAX 调用。

    【讨论】:

    • 谢谢,虽然遇到了一些_this.execute is not a function 错误。这是一个Vue 应用程序,我需要使用this.axios 调用Axios
    • 抱歉,我使用了匿名函数 this 在匿名 JS lambda 中不存在。立即尝试
    • 另外,您可以在dispatcher.execute 之外捕获此内容,我将更新我的答案以向您展示如何操作。编辑:通过在 dispatcher.execute 之外别名 this 更新为使用 this.axios
    • 谢谢,但仍然遇到同样的错误Uncaught (in promise) TypeError: _this.execute is not a function。我不明白为什么
    • 嗯..我已经更新了答案并在 AJAX 调用之外捕获了 dispatcher。试试看。在本地运行(不使用vm.axios)会给我预期的结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    • 2015-01-18
    相关资源
    最近更新 更多