var fs = require("fs");
var inquirer = require("inquirer");
var words = ["ALPHA","BRAVO","CHARLIE","DELTA","ECHO","FOXTROT","GOLF","HOTEL","INDIA","JULIET","KILO","LIMA","MIKE","NOVEMBER","OSCAR","PAPA","QUEBEC","ROMEO","SIERRA","TANGO","UNIFORM","VICTOR","WHISKEY","XRAY","YANKEE","ZULU"];
function nodeMan() {
var wrongs = 0;
var lettersGuessed = [];
var word = words[Math.floor(Math.random()*words.length)];
var goldenBoy = word.split("");
var blank = "_" * word.length;
console.log(blank);
for (var i = 0; wrongs < 10; i++) {
var neem = "Question " + i;
inquirer.prompt([{name: neem, message: "Guess a letter"}]).then(function(response) {
console.log("print");
lettersGuessed.push(resposne.name);
if (response.name.length < 1 && lettersGuessed.indexOf(response.name)) {
console.log(" first if statement cleared");
for (var u = 0; u < goldenBoy.length; u++) {
if (goldenBoy[u] === response.name) {
blank[u] = response.name;
console.log(blank);
}
}
}
})
}
}
nodeMan();
尝试以异步方式运行它。从那时起,我得到一个无限循环的“猜一封信”提示。需要帮助让询问者一次拍摄一个问题而不是无限制。谢谢你的时间!
设置测试文件夹不要忘记npm init和inquirer
答案 0 :(得分:0)
你不能使用for
循环并且需要使用递归:在你的问题的回答中,你需要决定是否要再问另一个问题并再次发出同样的问题(来自在你的回调中)。
这是一个基本的代码结构,可以帮助您:
function nodeMan()
const wrong = 0; // Store the number of wrong answers
const askQuestion = () => {
inquirer.prompt([{name: neem, message: "Guess a letter"}]).then((response) => {
// Here check the answer and decide if you want to ask another question
// [...]
wrong++;
// As long as less than 10 wrong answers, ask the question again
if (wrong < 10) {
// Ask the next question
askQuestion (); // Recursion !
}
}
};
}
nodeMan();
答案 1 :(得分:0)
如果您要在NodeJS 7.0+下运行代码,可以将函数声明为"async"函数,然后使用"await" operator等待for循环中的异步响应。
var fs = require("fs");
var inquirer = require("inquirer");
var words = ["ALPHA", "BRAVO", "CHARLIE", "DELTA", "ECHO", "FOXTROT", "GOLF", "HOTEL", "INDIA", "JULIET", "KILO", "LIMA", "MIKE", "NOVEMBER", "OSCAR", "PAPA", "QUEBEC", "ROMEO", "SIERRA", "TANGO", "UNIFORM", "VICTOR", "WHISKEY", "XRAY", "YANKEE", "ZULU"];
// declare an async function
async function nodeMan() {
var wrongs = 0;
var lettersGuessed = [];
var word = words[Math.floor(Math.random() * words.length)];
var goldenBoy = word.split("");
var blank = "_" + word.length;
console.log(blank);
for (var i = 0; wrongs < 10; i++) {
var neem = "Question " + i;
// wait for asynchronous response
var response = await inquirer.prompt([{
name: neem,
message: "Guess a letter"
}]);
console.log(response)
console.log("print");
lettersGuessed.push(response.name);
if (response.name.length < 1 && lettersGuessed.indexOf(response.name)) {
console.log(" first if statement cleared");
for (var u = 0; u < goldenBoy.length; u++) {
if (goldenBoy[u] === response.name) {
blank[u] = response.name;
console.log(blank);
}
}
}
}
}
nodeMan();