在提示时,有没有办法在询问者中使用以前的答案?

时间:2018-03-27 18:51:39

标签: javascript yo inquirer

所以我想要做的就是在进一步询问问题时使用之前的答案。基本上这样我就可以显示将要创建的内容的摘要并要求进行验证。

this.prompt([   
    {
      type: 'input',
      name: 'name',
      message: 'What is your name?'
      default: 'Jake'
    },
    {
      type: 'confirm',
      name: 'summary',
      message: 'Is this information correct? Your name is:' + answers.name',
    }

有一种简单的方法可以实现这一目标吗?或者另一种方法来实现列出所有先前答案的摘要类型事物?

4 个答案:

答案 0 :(得分:4)

就我而言,丹尼尔的答案不适用于查询者7。一种解决方法是将大提示分成多个,然后使用匿名JSON.stringify(obj)函数将它们包装起来。这将永远是安全的。

async

这将记录:

const inquirer = require("inquirer");

(async () => {
  const ans1 = await inquirer.prompt([
    {
      type: "input",
      name: "name",
      message: "What is your name?",
      default: "Jake",
    },
  ]);
  const ans2 = await inquirer.prompt([
    {
      type: "confirm",
      name: "summary",
      message: "Is this information correct? Your name is:" + ans1.name,
    },
  ]);
  return { ...ans1, ...ans2 };
})()
  .then(console.log)
  .catch(console.error);

答案 1 :(得分:1)

任何一个嵌套查询器调用:

inquirer
  .prompt({
    type: 'list',
    name: 'chocolate',
    message: "What's your favorite chocolate?",
    choices: ['Mars', 'Oh Henry', 'Hershey']
  })
  .then(() => {
    inquirer.prompt({
      type: 'list',
      name: 'beverage',
      message: 'And your favorite beverage?',
      choices: ['Pepsi', 'Coke', '7up', 'Mountain Dew', 'Red Bull']
    });
  });

或使用when函数。

{
  type: 'confirm',
  name: 'summary',
  message: 'Is this information correct? Your name is:' + answers.name',
  when: function( answers ) {
    // Only run if user set a name
    return !!answers.name;
  },
}

答案 2 :(得分:0)

const run = async () => {
  try {
    const ans1 = await inquirer.prompt([
      {},
    ]);

    const ans2 = await inquirer.prompt([
      {},
    ]);

    return { ...ans1, ...ans2 };

    inquirer.prompt([]);

  } catch (err) {
    if (err) {
      switch (err.status) {
        case 401:
          console.log('401');
          break;
        default:
          console.log(err);
      }
    }
  }
};

run();

答案 3 :(得分:0)

我参加聚会有点晚,但在寻找解决方案时遇到了这个问题。完整地说,在第 7 版中,可以将一个函数传递给 message 属性,从而得到如下答案:

inquirer
  .prompt([
    {
      type: "input",
      name: "name",
      message: "What is your name?",
    },
    {
      type: "list",
      name: "food",
      message: (answers) => `What would you like to eat ${answers.name}?`,
      choices: ["Hotdogs", "Pizza"],
    },
  ])
  .then((answers) =>
    console.log(`Enjoy your ${answers.food}, ${answers.name}!`)
  );