while(1){
rl.question("Command: ",function(answer){
console.log(answer);
})
}
刚刚尝试了这段代码,但不是一一输入,而是闪烁“命令:”行。我知道 Node.js 是非阻塞的,但我不知道如何解决这个问题。
var readline = require('readline');
var log = console.log;
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var recursiveAsyncReadLine = function () {
rl.question('Command: ', function (answer) {
if (answer == 'exit') //we need some base case, for recursion
return rl.close(); //closing RL and returning from function.
log('Got it! Your answer was: "', answer, '"');
recursiveAsyncReadLine(); //Calling this function again to ask new question
});
};
recursiveAsyncReadLine(); //we have to actually start our recursion somehow
关键是不要使用同步循环。接下来我们应该问rl.question
仅在处理答案后。递归是必经之路。我们定义提出问题并处理答案的函数,然后在答案处理后从内部调用它。这样我们就可以从头开始,就像常规循环一样。但是循环不关心 ansyc 代码,而我们的实现关心。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)