0

我正在使用Inquirer.js创建一个CLI's prompter允许users输入/回复某些输入/问题的应用程序。在最后一个问题中,我想添加一个功能,如果对问题的回复user,那么将重新开始提问,直到回复。我几乎可以使用该功能。noAre you done?prompteruseryes

它正在工作,但仅在我第一次进入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`);
    }
  });

4

1 回答 1

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.

于 2021-06-29T15:34:40.930 回答