使用node inquirer包返回值

时间:2017-07-16 15:04:56

标签: javascript node.js npm

我正在尝试使用node.js inquirer包来运行一个简单的flashcard生成器。我无法获取语法以返回用户单击的复选框。因此,一旦用户做出选择,我希望能够记录该选择的结果。目前这个console.log()返回“undefined”。

任何帮助表示赞赏!

inquirer.prompt ([
{
type: "checkbox",
name: "typeOfCard",
message: "Select an action.",
choices: [
  {
    name: "Create a Basic Card"
  },
  {
    name: "Create a Cloze Card"
  },
  {
    name: "Run the flashcards!"
  }
 ]
  }
   ]).then(function(answers){
 console.log(answers.typeOfCard[0])
});

2 个答案:

答案 0 :(得分:0)

const inquirer = require('inquirer');

inquirer.prompt ([
{
type: "checkbox",
name: "typeOfCard",
message: "Select an action.",
choices: [
  "Create a Basic Card",
  "Create a Cloze Card",
  "Run the flashcards!"
 ]
  }
   ]).then(function(answers){
 console.log(answers.typeOfCard);
});

choices应该只是一个字符串数组。然后,您将返回一个包含所选项目的数组,例如:

[ 'Create a Cloze Card', 'Run the flashcards!' ]

希望有所帮助!

答案 1 :(得分:0)

const inquirer = require("inquirer");

console.clear();

const main = async() => {

    const readCardChoise = () => {
        const read = new Promise((resolve, reject) => {
            inquirer.prompt ([
                {
                type: "checkbox",
                name: "typeOfCard",
                message: "Select an action.",
                choices: [
                      {
                        name: "Create a Basic Card"
                      },
                      {
                        name: "Create a Cloze Card"
                      },
                      {
                        name: "Run the flashcards!"
                      }

                 ],
                validate(answer) {
                if (answer.length < 1) {
                    return 'You must choose at least one card.';
                }
                return true;
                },
                  }])
                   .then((answers) => {
                    resolve(answers.typeOfCard);
                });
        });

        return read;

    }

    const cadSelect = await readCardChoise();
    console.log(cadSelect)

}

main();