gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:17:43 26 4
gpt4 key购买 nike

我正在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.

终端结果:未定义。

最佳答案

这并不是真正的工作原理 - 对于用户输入等异步操作,预计您将在回调中处理结果,而不是“等待”完成。您可以做的一件事是将代码包装在 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

关于javascript - Node.js - 如何将 readline 答案存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54468349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com