我猜那是一个棘手的问题。我正在提示用户输入一个用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
}
}
}