【问题标题】:How to Pause a While Loop While Waiting for User Command-line Input?如何在等待用户命令行输入时暂停 While 循环?
【发布时间】:2021-09-27 21:50:51
【问题描述】:

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

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

不幸的是,我必须在这种情况下使用 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;
}

【问题讨论】:

  • 不是这样,你需要使用for await循环
  • @MisterJojo 在while 循环中的await 也可以工作。
  • @Bergi 我在 mdn 中没有找到while await,如for await
  • @MisterJojo 我的意思是awaitwhile 循环的body 中。除非您正在处理异步迭代器(readline.question 不是),否则不要使用 for await … of

标签: javascript node.js while-loop readline


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2016-02-15
    • 2014-12-24
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 2012-11-10
    • 2012-10-13
    • 2018-03-23
    • 1970-01-01
    相关资源
    最近更新 更多