Node.js无限循环function,在某些用户input时退出

我并不十分清楚节点是如何处理asynchronous和循环的。 我想在这里实现的是控制台打印出“ 命令: ”并等待用户的input。 但是在等待的时候,我希望它不停地运行“ someRandomFunction() ”,直到用户input“exit”到terminal上。

将感谢所有的帮助 – 可能的解释,所以我可以理解!

谢谢! 🙂

var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("Command: ", function(answer) { if (answer == "exit"){ rl.close(); } else { // If not "exit", How do I recall the function again? } }); someRandomFunction(); 

我会build议使function重复如此。

 var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); var waitForUserInput = function() { rl.question("Command: ", function(answer) { if (answer == "exit"){ rl.close(); } else { waitForUserInput(); } }); } 

然后打电话

 waitForUserInput(); someRandomFunction(); 

我不确定你使用.question的语法是否正确,但是这部分代码是否工作?

你也可以这样写下来。

 var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); function waitForUserInput() { rl.question("Command: ", function(answer) { if (answer == "exit"){ rl.close(); } else { waitForUserInput(); } }); } 

这里重要的一个教训是重用一个函数,它必须被命名并在范围内可用。 如果您对此有任何疑问,请询问。