Can you create a while loop that continuously asks for user input, stores the responses, and then makes them accessible in an array?

When developing a Yeoman generator, the necessary dependencies can be found at https://github.com/sboudrias/mem-fs-editor#copytplfrom-to-context-settings and https://github.com/SBoudrias/Inquirer.js/.

The main goal is to prompt the user with a question and repeat it as needed. For instance, if the user chooses to add more details, the answer will be recorded. If the response is 'no' or blank, the prompt should stop.

Subsequently, all answers should be stored in an array that can be passed to another function for listing out responses. Take a look at the current code:

askForTest1: function () {
    if (this.type == 'foundation5') {
        var cb = this.async();

        var prompts = {
            type: 'input',
            name: 'test1',
            message: chalk.yellow('  What is your favorite movie'),
            default: 'Star Wars!'
        };

        this.prompt(prompts, function (props) {
            this.templatedata.test1 = props.test1;

            cb();
        }.bind(this));
    }
},

Following the prompts, there is a copyTpl object that assigns options for creating templates. This is the intended output I am aiming for within the same index.js file:

this.fs.copyTpl(
      this.templatePath('/index2.html'),
      this.destinationPath('app/index2.html'),
      { title: [this.templatedata.test1-a, this.templatedata.test1-b, this.templatedata.test1-c, ...], h1: this.applicationName }
);

Ultimately, the template code mentioned should yield the following result:

using

This would generate:

using foo1
using foo2

Is this achievable? How should I approach implementing this functionality?

Answer №1

This task involves a simple programming exercise.

The method uses recursion to repeatedly ask the user a question. If the user responds with "yes, add more", the function is called again.

Here is an example of how it can be implemented:

initialize: function () {
  this.collection = [];
},

askItem: function (callback) {
  callback = callback || this.async();

  var prompts = [{
      type: 'input',
      name: 'item',
      message: chalk.yellow('  Enter your favorite item'),
      default: 'Star Wars!'
  }, {
    type: 'confirm',
    name: 'askAgain',
    message: 'Ask again?'
  }];

  this.prompt(prompts, function (properties) {
    this.collection.push(properties.item);
    if (properties.askAgain) {
      this.askItem(callback);
    } else {
      callback();
    }
  }.bind(this));
}

Answer №2

If you're looking for a solution, try something along these lines:

function() {
    var info = {
        times: [],
        title: undefined,
        type: undefined
    };

    function askQuestion(question, callback) {
        self.prompt(question, function (response) {
            if(response.answer != "done") {
                info.times.push(response.time);
                askQuestion(question, callback);
            } else {
                callback();
            }
        });
    }

    var callback = this.async(),
        self = this,
        movieTypeQuestion = {
            type: 'input',
            name: 'movieType',
            message: chalk.yellow('What is your favorite type of movie?'),
            default: 'Action'
        },
        movieTitleQuestion = {
            type: 'input',
            name: 'movieTitle',
            message: chalk.yellow('What is your favorite movie?'),
            default: 'Tron: Legacy'
        }
        movieTimeQuestion = {
            type: 'input',
            name: 'time',
            message: chalk.yellow('When can you watch a movie? (enter \'done\' when you are done entering times)'),
            default: '8PM'
        };

    //Prompt for movie type and title
    this.prompt([movieTypeQuestion, movieTitleQuestion], function (response) {
        info.title = response.movieTitle;
        info.type = response.movieType;

        //Keep asking for movie times
        askQuestion(movieTimeQuestion, function() {
            console.log('done');

            callback();
        });
    }.bind(this));
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The results from various <div> elements are displayed based on the selection made from the dropdown menu

<body> <label for="country">Country : </label> <select id="country"> <option>Please select</option> <option name="CountryRevenue">Revenue</option> <option name="CountryQuantity">Quantity ...

Trouble with retrieving dates in ISO format

My collection stores the date of birth field in ISO format, for example: ISODate("1980-01-01T20:20:19.198Z") However, when I use a date time picker on my HTML page, it displays the date like this: 01/01/1980 Unfortunately, when querying for the date of ...

Executing multiple Ajax requests on CodeIgniter 3 from two separate pages

I am facing a critical need for a code review and unfortunately, I am unsure of where else to seek assistance besides here. Let me outline my current task: I am working on a user profile page that is designed to showcase users' comments. Users have t ...

Attempting to navigate the world of AJAX and PHP

My experience with AJAX is limited, but I am currently working on a project that requires a form to submit data without refreshing the page. The goal is to display the result in a modal window instead. To achieve this functionality, I understand that imple ...

Using VueJS to determine if a certain string includes a specific substring within an if-statement embedded within a v

I am aiming to verify if the link in a json object contains 'http'. If it does, I want to assign a target='_blank' attribute to the v-btn. The link could also be something like #test. Currently, this is how I am attempting to achieve i ...

Retrieve the ID from either a search query or an insertion operation in MongoDB

I find myself frequently using this particular pattern. It feels a bit cumbersome to make two MongoDB calls for the task, and I am curious if there is a more efficient way to achieve this. My goal is to obtain the ID of an existing document, or.. create ...

What is the best situation to utilize $(document).ready()?

After observing that using $(document).ready(..) seems to introduce a noticeable delay in applying JavaScript effects, I've been contemplating the best approach. I know that simply placing the effect in a <script> tag may not work if the DOM isn ...

Using Selenium Webdriver with C# to dynamically expand a RadMenu Webelement in Javascript

I am currently working with Selenium WebDriver in C# and facing an issue with a RadMenu. My goal is to hover over the menu so that it expands a sub menu, where I can find a specific webelement to click. I have tried using JavaScript for this purpose, but u ...

Differences between Array and Database Search

Currently, I have implemented a system where I store a refresh token in a JavaScript array as well as in each user's information table. When a user requests data, I first check the token in the array. If the token matches one in the array, I loop thro ...

Repeated information in HTML tables

I am currently working with two HTML tables and two sets of JSON data. Initially, I load one table with the tableData which has a default quantity of 0. In my HTML form, there are three buttons - save, load draft, and edit. Upon clicking on load draft, I p ...

Hey Webapp: Access denied - unable to open 'Gruntfile.js' due to permissions

Ever since I switched to Linux, I have been encountering the "Error EACCESS, permission denied" message whenever I try to install any Yeoman generator. fs.js:432 return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode); ...

Creating a new URL using a JSON response in Node.js: A step-by-step guide

I am facing a query regarding the following code: The issue at hand is: How can I pass each line from response promiseGetCitiesData to promiseGetInformationDataPerCity. Is it possible to achieve this in a single async.each function? Currently, I have ...

Issue with Chart.js not showing up in Android Webview when animation is disabled

I am experiencing an issue with a javascript enabled WebView using a ChromeWebClient. The Chart.Js pie example displays fine until I set the options to animation: false, after which the chart stops displaying. var pieOptions = { animation : fa ...

The specified element type is not valid: only a string (for built-in components) or a class/function is expected when attempting to display a component

`Unhandled Runtime Error Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you mi ...

Navigating over two JSON arrays using Ajax

My goal is to fetch data from a JSON file by utilizing the ID obtained from a previous AJAX call and looping through the second array based on the retrieved ID. I have attempted to achieve this with the following code: $(document).on('click', ...

What is the optimal approach for moving the dashboard to a separate subdomain in a static Next.js-generated landing page?

Our current setup includes several static pages generated by Next.js using the command next build && next export These pages are hosted on AWS S3. I am wondering if we should create a new app for building a dashboard with Firebase authentication ...

Setting up dependencies using npm workspaces

I have been utilizing npm workspaces and have encountered the need to individually build each project. When using npm ci, it installs dependencies for all packages including root dependencies. On the other hand, running npm ci -w @project/foo will only i ...

Is there a way to handle button click event when utilizing this.props.children in React?

I have recently completed a React component that serves as a modal wrapper. The content for this modal is passed through the props.children property. Inside the content, there is a button that, when clicked, should trigger an event in the parent component. ...

The function for utilizing useState with a callback is throwing an error stating "Type does not have

Currently, I am implementing the use of useState with a callback function: interface Props { label: string; key: string; } const [state, setState] = useState<Props[]>([]); setState((prev: Props[]) => [...pr ...

Tips on retrieving and sending an XML string in PHP to JavaScript using MySQL

Here is the code snippet I have: <input type='button' value='clickme' onclick='download(\"\" . $rowtable['Protocolo'] . \".xml\", \"\" . $rowtable['XML&a ...