我正在开发一个节点猜词游戏,并且我尝试编写代码来提示用户输入,直到他们用完猜词或正确猜出单词为止。现在我在处理提示的回调时遇到问题。由于回调的性质,在最终等待用户输入之前,我的代码会遍历每个单词的所有“提示”代码。我曾尝试使用forEach和while循环。后来尝试设置诺言,但我什么都没想。
for(i = 0; i < wordsInPlay.length; i++){
if(losses < 3){
let solved = false;
wordThisRound = new Word(wordsInPlay[i]);
wordThisRound.setupWord();
getGuess();
}
}
这是getGuess函数实现提示nod.js包的方法:
function getGuess() {
wordThisRound.updateWordDisplay();
if (wrongsLeft > 0) {
new Promise(function(resolve) {
prompt.get(guessObject, function(err, result) {
console.log('line 68');
if(err) throw err;
let userGuess;
const letterGuessed = result.guess.toLowerCase();
if (wordThisRound.wordObject.hasOwnProperty(letterGuessed) && wordThisRound.wordObject[letterGuessed].guessed === false) {
userGuess = true;
wordThisRound.wordObject[letterGuessed].guessed = true;
wordThisRound.wordObject[letterGuessed].changeDisplay();
}
else {
userGuess = false;
wrongsLeft--;
}
resolve({gussedRight: userGuess, letter: letterGuessed});
});
}).then(function(promise){
console.log('Inside .then function.');
new Promise(function(resolve){
gameFeedback(promise.gussedRight, promise.letter);
resolve();
});
}).then(function(){
getGuess();
});
}
else console.log("You're our of wrong guesses...You lost this round.");
}