'Series of user inputs in javascript using readline where corresponding questions are stored in array
I've stored few questions in an array var questions=[]. I'm using forEach to traverse through the array and take input for each and every question and display it on the terminal itself. But it is asking only the first question, displays the response and stays there. It is not shifting to the next question. I should use rl.close(), but where. Here is my code 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
}
Please correct me.
Solution 1:[1]
Did you try to close it after all questions are asked?
I mean this:
function myFunction(item, index) {
rl.question(item, (answer) => {
console.log(`You said: ${answer}`);
});
if (index === questions.length - 1) {
rl.close();
}
}
=== === ===
If it's still not working try this:
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)
I closed the rl outside the askAll function, because I think it's better for the function not to know about such thing as resource management.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
