首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >继续使用基于答案的Inquirer.js重复提示器问题?

继续使用基于答案的Inquirer.js重复提示器问题?
EN

Stack Overflow用户
提问于 2021-06-29 05:04:59
回答 1查看 166关注 0票数 0

我正在使用Inquirer.js创建一个CLI's prompter,它允许users输入/回答一些输入/问题。在最后一个问题中,我想添加一个功能,如果user回复noAre you done?问题,那么prompter将重新开始提问,直到user回复yes。我的功能就快完成了。

它起作用了,但只在我第一次进入no的时候。第二次进入no时,提示器停止。

我如何才能在循环中运行它来完成所需的行为?我哪里做错了?

这是我目前掌握的一些信息:

代码语言:javascript
复制
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`);
    }
  });
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-29 23:34:41

一种方法是使用递归函数:

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68170024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档