Node js rl重复上次提示

这似乎是应该很容易做的事情,但我找不到在文档中的任何东西。

我有一系列我想问的问题,其中一个我想重新提问,直到我得到一个有效的答案。 喜欢这个:

rl.question('Author: ', function(answer) { //question #1 author = answer; //Use that value, move to next question rl.question('What Title should be shown in browser tabs for this site? ', function(answer) { //question #2 title = answer; //Move on... rl.question('Include the tippy.js library? ', function(answer) { //question #3 if (answer == 'y' || answer == 'yes' || answer == 'Yes' || answer == 'Y') { console.log("Will include tippy.js"); //Done with app } else if (answer == 'n' || answer == 'no' || answer == 'N' || answer == 'No') { console.log("Will not include tippy.js"); //Done with app } else { console.log("Invalid response"); //Re-ask question #3 without asking questions #1 and #2 } }); }) }); 

build议? 感谢您的考虑。

你可以把它放在一个函数中,然后每次需要重复时调用该函数。

 function shouldIncludeTippy() { rl.question('Include the tippy.js library? ', function(answer) { if (answer === 'y' ...) { console.log('Will include tippy.js'); } else if (answer === 'n' ...) { console.log('Will not include tippy.js'); } else { console.log('Invalid response'); shouldIncludeTippy(); } }); } 

那么你的代码是这样读的:

 rl.question('Author: ', function(answer) { //question #1 author = answer; //Use that value, move to next question rl.question('What Title should be shown in browser tabs for this site? ', function(answer) { //question #2 title = answer; //Move on... shouldIncludeTippy(); }) });