读取用户输入,直到答案正确为止

时间:2019-07-19 10:06:56

标签: javascript node.js

我有一个猜谜游戏,用户必须找出一个单词。我使用Readline模块获取用户的输入。如果用户的猜测是错误的,则应再次提出问题。这是我的代码:

const readline = require("readline").createInterface({
    input: process.stdin,
    output: process.stdout
});

let answer;
const word = "Pancakes"

while (answer != word) {
    readline.question("Guess the word: ", input => {
        answer = input;
        readline.close();
    });
}

我也已经尝试过:

const word = "Pancakes";
let isright = false;

while (!isright) {
    readline.question("Guess the word: ", input => {
        isright = input == word;
        readline.close();
    });
}

结果相同:控制台闪烁“猜单词:”,因此我认为循环甚至在获得用户输入之前就一直在继续。为什么会这样?

1 个答案:

答案 0 :(得分:0)

这是因为while是synchronousreadline.question是异步的。您需要递归调用该问题。或需要设置prompt并递归提示另一个,依此类推。

const readline = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout
});

const word = "Pancakes"
readline.setPrompt('Guess the word: ');
readline.prompt();

readline.on('line', function(input) {
  if(input !== word){
    readline.prompt();
  }else{
    readline.close()
  }
}).on('close', function() {
    console.log('Closed');
    process.exit(0);
});