问题描述
我正在使用NodeJS。
我有以下任务:
- 接受用户输入“计数”表示用户应输入数据的次数。
- 接受基于计数的多个输入,例如,如果count为5,则允许用户输入5次输入。
我面临的问题是如何基于用户首次输入的“计数”来同步获取用户输入。
例如,如果有C ++代码,我可以简单地循环“计数”并同步接受输入。
如何在NodeJS中实现相同目标?
解决方法
由于采用Javascript async-io事件循环体系结构,因此实施解决方案比较棘手。 有多种解决Java问题的方法,我为您提供了2种方法。
解决方案1
这是“旧的”处理方式。此解决方案使用@IBAction func didBeginMove(_ sender: CurrencyField) {
}
和callbacks
。我不会个人使用,但这是操纵JS事件循环的一个很好的例子。
recursion
解决方案2
此解决方案是编写JS的“现代”方法。它使用const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,output: process.stdout
});
rl.question("Enter inputs count: ",function (countRaw) {
// validate count
const count = parseInt(countRaw);
readMultipuleInputs(count,count,(res) => {
console.log(res)
rl.close();
})
});
function readMultipuleInputs(count,maxCount,cb) {
if (count == 0) {
cb([]);
}
const currentCount = maxCount-count+1;
rl.question(`Enter input (${currentCount}/${maxCount}): `,function (res) {
readMultipuleInputs((count - 1),(accumulator) => {
accumulator.unshift(res);
cb(accumulator);
});
});
}
rl.on("close",function () {
console.log("\nBYE BYE !!!");
process.exit(0);
});
和async
允许您将代码视为同步代码。
await