Search code examples
javascriptnode.jswhile-loopreadline

How to Pause a While Loop While Waiting for User Command-line Input?


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;
}


Solution

  • I did it, but I have almost no clue how it works!

    const readline = require("readline");
    
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
    });
    
    var userInput = 0;
    var sum = 0;
    
    const numFunc = async () => {
      while (userInput !== -1) {
        const answer = await new Promise((resolve) => {
          rl.question(
            "Enter a positive number to be added to the total or -1 to end. ",
            resolve
          );
        });
        userInput = parseInt(answer);
        if (answer != -1) sum += parseInt(answer);
      }
      console.log("The sum of all numbers entered is " + sum);
      rl.close();
    };
    
    numFunc();