Node.js - 如何将 readline 答案存储在变量中

Node.js - How to store readline answer in a variable

我正在 node.js 中建造 Yahtzee。我使用下面的代码要求用户输入。答案需要存储在一个变量中。我假设 [answer] 用于临时存储答案值,但是如何在不对代码结构进行太多更改的情况下将 [answer] 导出到数组?

基本代码结构:

const readline = require('readline');

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

rl.question("Which dices to keep [1,2,3,4,5] ?: ", (answer) => {
  console.log("Will keep dices: ", answer);
  rl.close();
});

扩展基本代码结构,将用户输入的答案添加到变量中:

var lines;                                 // Added compared to basic code.
const readline = require('readline');
const rl = readline.createInterface({
  input:  process.stdin,
  output: process.stdout
});
rl.question("Which dices to keep [1,2,3,4,5] ?: ", (answer) => {
  lines.push(answer);                      // Added compared to basic code.
  console.log("Will keep dices: ", answer);
  rl.close();
});
console.log(lines);                        // Added compared to basic code.

来自终端的结果:未定义。

实际情况并非如此 - 对于用户输入等异步操作,您应该在回调中处理结果,而不是 "waiting" 完成。您可以做的一件事是将您的代码包装在 Promise 中,如下所示:

const readline = require('readline');

function getDiceAnswer() {
    return new Promise(resolve => {    
        const rl = readline.createInterface({
            input:  process.stdin,
            output: process.stdout
        });
        rl.question("Which dices to keep [1,2,3,4,5] ?: ", (answer) => {
            resolve(answer);
            console.log("Will keep dices: ", answer);
            rl.close();
        });
    });   
}

这仍然意味着您需要在回调中处理结果:

const lines = [];
getDiceAnswer().then(answer => {
     lines.push(answer);
     console.log(lines);
});

...但是您可以使用 Javascript async/await 符号使其看起来更好:

async function getAnswers() {
     const diceAnswer = await getDiceAnswer();

     //this line won't execute until the answer is ready
     lines.push(diceAnswer);
}

另一种简单的替代方法是使用像 readline-sync 这样的包来使操作同步:https://www.npmjs.com/package/readline-sync