I want to output questions and receive answers as input in a terminal. For each question, there is a check, in this case if the input was provided or not. If it is, next question should be outputted; if not, question should be looped.
If input is provided every time, resolve()
gets called and moves on to the next question, as it should. But the problem happens if the first time an empty input is sent. It kinda gets stuck and the resolve()
does not work any more
const rdline = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let userName, userSurname = "";
1st question
const question_name = () => {
return new Promise((resolve) => {
rdline.question("What's your name?\n", name => {
if (name) {
userName = name;
resolve();
} else {
question_name();
}
});
});
};
2nd question
const question_surname = () => {
return new Promise((resolve) => {
rdline.question("What's your surname?\n", surname => {
if (surname) {
userSurname = surname;
resolve();
} else {
question_surname();
}
});
});
};
call both questions
const askUser = async () => {
await question_name();
await question_surname();
console.log(`Hi, ${userName} ${userSurname}`);
rdline.close();
};
askUser();