簡體   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