我正在使用Inquirer.js创建一个CLI's prompter,它允许users输入/回答一些输入/问题。在最后一个问题中,我想添加一个功能,如果user回复no到Are you done?问题,那么prompter将重新开始提问,直到user回复yes。我的功能就快完成了。
它起作用了,但只在我第一次进入no的时候。第二次进入no时,提示器停止。
我如何才能在循环中运行它来完成所需的行为?我哪里做错了?
这是我目前掌握的一些信息:
import inquirer from 'inquirer';
inquirer
.prompt([
// { bunch of other questions previously },
{
type: 'confirm',
name: 'repeat_questions',
message: 'Are you done?',
},
])
.then((answers) => {
if (answers.repeat_questions) {
return inquirer.prompt([
// { bunch of other questions previously },
{
type: 'confirm',
name: 'repeat_questions',
message: 'Are you done?',
},
]);
}
})
.catch((error) => {
if (error.isTtyError) {
throw new Error(`Prompt couldn't be render in current environment`);
}
});发布于 2021-06-29 23:34:41
一种方法是使用递归函数:
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也是no。因此,我将其重命名为is_finished。
https://stackoverflow.com/questions/68170024
复制相似问题