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

Series of user inputs in javascript using readline where corresponding questions are stored in array

我在一个数组中存储了几个问题 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
}

请指正。

问完所有问题后,您是否尝试关闭它?

我的意思是:

function myFunction(item, index) {
  rl.question(item, (answer) => {
    console.log(`You said: ${answer}`);
  });

  if (index === questions.length - 1) {
     rl.close();
  }
}

=== === ===

如果还是不行试试这个:

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?',
];

const ask = (question) => {
  return new Promise(resolve => rl.question(question, resolve))
}

const askAll = async (questions) => {
  const answers = []

  for (let q of questions) {
    answers.push(await ask(q))
    console.log('You said:', answers[answers.length - 1]);
  }

  return answers
}

askAll(questions).then(rl.close)

我关闭了askAll函数外的rl,因为我觉得这个函数最好不要知道资源管理之类的东西。

您想一个问题提出问题,然后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);
})();