【发布时间】: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 我的意思是
await在while循环的body 中。除非您正在处理异步迭代器(readline.question不是),否则不要使用for await … of。
标签: javascript node.js while-loop readline