繁体   English   中英

Function 没有进入第二个 if 块

[英]Function doesn't make it to the second if block

我想从 stdin 读取多行,不幸的是,无论我选择哪个选项,我的代码都不会通过第一个 if 块。

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
function clientOpener(){
  rl.question("Choose a number:\n1)Start a bowling game\n2)Exit simulation\n", function (startGame) {
    const y = "1";
    const n = "2";
    if(y === startGame){
      (async () => {
        const playerCount = await rl.question("Ok how many players will there be (MAX: 8 players)\n");
        const parsedInput = parseInt(playerCount);
        if (parsedInput > 0 && parsedInput <= 8) {
            let listOfNames = [];
            for (let i=0; i<parsedInput; i++) {
                const name = await rl.question(`Enter name #${i}\n`);
                listOfNames.push(name);
                console.log(`Added ${name} to list of players\n`);
            }
            console.log(listOfNames);
        }
        rl.close();
      })();
    }
    else if(n === startGame){
      console.log("Ending interface");
      rl.close();
    }
    else {
      console.log("Please enter a valid option");
      clientOpener();
    }
  });
}
clientOpener();

控制台 output(同样的 output 发生在 else if 和 else 选项上):

1)Start a bowling game
2)Exit simulation
1
*console unresponsive*

您的尝试中有几处出错了。 有问题的一件事是,您正在尝试将 readlines question与 await 一起使用,为此您需要 NodeJS 内置的 readline/promises package。 下面的代码使用了 readline 的异步版本,并且似乎在做你想要的。

const process = require("process");
const readline = require("readline/promises");

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

async function clientOpener(){
  let startGame = await rl.question("Choose a number:\n1)Start a bowling game\n2)Exit simulation\n");
  const y = "1";
  const n = "2";
  if(y === startGame){
    let playerCount = await rl.question("Ok how many players will there be (MAX: 8 players)\n");
    const parsedInput = parseInt(playerCount);
    if (parsedInput > 0 && parsedInput <= 8) {
      let listOfNames = [];
      for (let i=0; i<parsedInput; i++) {
        let name = await rl.question(`Enter name #${i}\n`);
        listOfNames.push(name);
        console.log(`Added ${name} to list of players\n`);
      }
      console.log(listOfNames);
    }
    rl.close();
  }
  else if(n === startGame) {
    console.log("Ending interface");
    rl.close();
  } else {
    console.log("Please enter a valid option");
    clientOpener();
  }
}

clientOpener();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM