gpt4 book ai didi

javascript - 使用 readline 在 javascript 中进行一系列用户输入,其中相应的问题存储在数组中

转载 作者:行者123 更新时间:2023-12-01 00:48:34 25 4
gpt4 key购买 nike

我在数组 var questions=[] 中存储了一些问题。我使用 forEach 遍历数组并获取每个问题的输入并将其显示在终端本身上。但它只问第一个问题,显示响应并停留在那里。它不会转移到下一个问题。我应该使用 rl.close(),但是在哪里。这是我的代码 Quiz.js

const readline = require('readline');

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

var questions=[
"Hi, What is your name?",
"I need your contact number also",
"Thanks! What is your favourite color?"
];

questions.forEach(myFunction);

function myFunction(item, index) {
rl.question(item, (answer) => {
console.log(`You said: ${answer}`);
});
rl.close(); //THIS IS IMMEDIATELY CLOSING AFTER THE FIRST QUESTION
}

请纠正我。

最佳答案

您想要一一提出问题,然后在提出所有问题后close()

const readline = require('readline');

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

let questions = [
'Hi, What is your name?',
'I need your contact number also',
'Thanks! What is your favourite color?',
];

(async () => {
let answers = [];

// asking questions one by one
for (let question of questions) {

// wait for the answer
let answer = await new Promise(resolve => rl.question(question, resolve));

console.log(`You said: ${answer}`);

answers.push(answer);
}

// close at the end
rl.close();

console.log(answers);
})();

关于javascript - 使用 readline 在 javascript 中进行一系列用户输入,其中相应的问题存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57176074/

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