javascriptnode.jscommand-line-interfacepromptinquirerjs

Keep repeating the prompter questions with Inquirer.js based on answer?


I'm using Inquirer.js to create a CLI's prompter which allows users to enter/reply to some input/questions. In the last question, I want to add a feature that if the user replies no to Are you done? question, then the prompter will restart asking the questions until the user replies yes. I'm almost there with the functionality.

It's working, but only on the first time when I enter no. The second time I enter no, the prompter stops.

How can I run this on a loop to accomplish the desired behavior? What I'm doing wrong?

This is what I have some far:

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`);
    }
  });


Solution

  • One way is a recursive function:

    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) => {});
    

    The variable repeat_questions doesn't make sense, if the user says no to if they are done, repeat_questions is also no. So instead I renamed it to is_finished.