如何在等待用户命令行输入时暂停 While 循环?

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

在每个循环之前,如何在每个后续循环之前等待用户响应?

这个 while 循环应该无限期地接受用户的命令行输入并将其添加到总和中。如果用户输入是-1,那么它应该停止循环并且return总和。

不幸的是,我必须在这种情况下使用 while 循环,虽然我知道这不是最好的方法,只是为了学习。

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

我做到了,但我几乎不知道它是如何工作的!

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