【问题标题】:Keep repeating the prompter questions with Inquirer.js based on answer?根据答案不断重复使用 Inquirer.js 的提示问题?
【发布时间】:2021-09-11 03:38:50
【问题描述】:

我正在使用Inquirer.js 创建一个CLI's prompter,它允许users 输入/回复一些输入/问题。在最后一个问题中,我想添加一个功能,如果user 回复noAre 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`);
    }
  });

【问题讨论】:

    标签: javascript node.js command-line-interface prompt inquirerjs


    【解决方案1】:

    一种方法是递归函数:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-26
      • 2018-09-15
      • 2021-05-05
      • 2023-03-31
      • 2019-08-25
      • 1970-01-01
      • 2023-02-14
      • 2015-02-22
      相关资源
      最近更新 更多