【发布时间】: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