猿问

使用 readline 在 javascript 中输入的一系列用户输入

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

}

请纠正我。


牛魔王的故事
浏览 352回答 2
2回答

萧十郎

我在 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}请纠正我。

MMTTMM

问完所有问题后,您是否尝试关闭它?我的意思是: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)我关闭了函数的rl外部askAll,因为我认为函数最好不要知道资源管理之类的东西。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答