内容简介:翻译自:https://stackoverflow.com/questions/24464404/how-to-readline-infinitely-in-node-js
while(1){ rl.question("Command: ",function(answer){ console.log(answer); }) }
刚刚尝试了这段代码,但是逐个输入,它会使“Command:”行闪烁.我知道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
关键是不要使用同步循环.我们应该在处理答案后才问下一个问题.递归是要走的路.我们定义函数,询问问题并处理答案,然后在答案处理后从内部调用它.这种方式我们从头开始,就像常规循环一样.但循环不关心ansyc代码,而我们的实现关心.
翻译自:https://stackoverflow.com/questions/24464404/how-to-readline-infinitely-in-node-js
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Introduction to Linear Optimization
Dimitris Bertsimas、John N. Tsitsiklis / Athena Scientific / 1997-02-01 / USD 89.00
"The true merit of this book, however, lies in its pedagogical qualities which are so impressive..." "Throughout the book, the authors make serious efforts to give geometric and intuitive explanations......一起来看看 《Introduction to Linear Optimization》 这本书的介绍吧!