I'm trying to get an input from the keyboard by calling a function that uses the built-in readline module, but it seems that the loop "doesn't wait" for each function call to finish.
The main function is supposed to print the 4 different numbers that are inputted.
I've tried using async-await on my main function, but that had the same result. Is async-await even needed for this?
I'm using the command node input.js in terminal to run the program. No HTML.
function getInput(question) {
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question(question, function (x) {
var aString = parseInt(x);
rl.close();
entered = true;
return aString;
});
}
async function main() {
var i = 0;
var myGuess;
while (i <= 3) {
myGuess = await getInput("Enter something: ");
console.log(myGuess);
i++;
}
}
main();
I expect to see:
Enter something: 3 // just entering random numbers
3
Enter something: 9
9
Enter something: 12
12
Enter something: 55
55
But I get:
Enter something: undefined
Enter something: undefined
Enter something: undefined
Enter something: undefined
2222 // I only got to enter 2...