Before each loop, how can I wait for a user response before each subsequent loop?
This while loop should indefinitely take a users command-line input and add it to the sum. If the users input is -1, then it should stop the loop and return the total sum.
Unfortunately, I must use a while loop for this scenario although I know that its not the best way, its just to learn.
var userInput = 0;
var sum = 0;
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
while (userInput !== -1) {
readline.question(
`Enter a positive number to be added to the total or -1 to end.`,
(num) => {
userInput = num;
readline.close();
}
);
sum += userInput;
}
awaitin awhileloop would also work.while awaitin mdn, as for awaitawaitin the body of awhileloop. Unless you're dealing with asynchronous iterators (whichreadline.questionis not), don't usefor await … of.