javascriptasynchronousinquirerjs

Passing an answer to choices in InquirerJS?


How would I be able to get an answer from a previous question and pass on to the next question for choices for inquirerJS? I know the fact that it is asynchronous but i'm not sure how to create promises here. Any further insight and help would be great.

Example:

var questions = [{
    name: 'menu',
    type: 'checkbox',
    message: 'Which food do you like eating?',
    choices: ['pizza', 'hotdog', 'hamburger', 'sandwiches'],
   }, {
    name: 'favorite',
    type: 'checkbox',
    message: 'Which one do you like most?',
    choices: answers.menu,   <------- doesn't work because it is asynchronous
   };

Solution

  • According to the documentation choises can be a function.

    var inquirer = require('inquirer');
    
    var questions = [
      {
        name: 'menu',
        type: 'checkbox',
        message: 'Which food do you like eating?',
        choices: ['pizza', 'hotdog', 'hamburger', 'sandwiches'],
      },
      {
        name: 'favorite',
        type: 'checkbox',
        message: 'Which one do you like most?',
        choices: (answers) => {
            return answers.menu;
        }
      },
    ];
    
    inquirer.prompt(questions).then(answers => {
      console.log(answers);
    });