节点js rl重复最后一个提示

时间:2017-12-13 17:02:02

标签: javascript node.js

这似乎应该很容易做到,但我无法在文档中找到任何内容。

我想问一系列问题,其中一个我想重新询问,直到得到有效答案。像这样:

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
            }
        });
    })
});

连连呢?谢谢你的考虑。

1 个答案:

答案 0 :(得分:1)

您可以将其粘贴在一个函数中,然后在每次需要重复时调用该函数。

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();
    })
});