0

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

4
  • not this way, you need to use an for await loop Commented Sep 27, 2021 at 23:10
  • @MisterJojo An await in a while loop would also work. Commented Sep 27, 2021 at 23:45
  • @Bergi I didn't found a while await in mdn, as for await Commented Sep 27, 2021 at 23:50
  • @MisterJojo I mean an await in the body of a while loop. Unless you're dealing with asynchronous iterators (which readline.question is not), don't use for await … of. Commented Sep 27, 2021 at 23:53

1 Answer 1

1

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();

Sign up to request clarification or add additional context in comments.

1 Comment

I learned async js, so looking back now it was just an async issue lo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.