drake035
drake035

Reputation: 2897

How to exit a while loop depending of the result of an Axios call?

In order to make sure a user-entered word exists, I need to keep prompting (while loop) for a word until the word API finds the word.

My question is: how can I exit the while loop depending of Axios call result?

Below is my code so far.

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

Upvotes: 0

Views: 366

Answers (1)

gabriel.hayes
gabriel.hayes

Reputation: 2313

Try this:

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

Rather than using a while loop or using an async/await you can use recursion in our promise. If the result is not satisfied, re-run the AJAX call.

Upvotes: 1

Related Questions