问题描述
我正在使用 Inquirer.js 创建一个 CLI's prompter
,它允许 users
输入/回复某些输入/问题。在最后一个问题中,我想添加一个功能,如果 user
对 no
问题回复 Are you done?
,那么 prompter
将重新开始提问,直到 {{1 }} 回复 user
。功能差不多了。
它有效,但仅在我第一次输入 yes
时有效。我第二次输入 no
时,提示器停止。
如何在循环中运行它以完成所需的行为?我做错了什么?
这就是我所拥有的:
no
解决方法
一种方法是递归函数:
import inquirer from "inquirer";
const questions = [
{
type: "number",name: "children_count",message: "How many children do you have?",},{
type: "input",name: "first_child_name",message: "What is the eldest child's name?",{
type: "confirm",name: "is_finished",message: "Are you done?",];
function getAnswers() {
return inquirer.prompt(questions).then((answers) => {
if (answers.is_finished) {
return answers;
} else {
return getAnswers();
}
});
}
getAnswers()
.then(console.log)
.catch((error) => {});
变量 repeat_questions
没有意义,如果用户说不,如果他们完成了,repeat_questions
也是不。因此,我将其重命名为 is_finished
。