【问题标题】:Return answer of inquirer prompt inside of another function在另一个函数中返回询问者提示的答案
【发布时间】:2019-05-02 20:17:12
【问题描述】:

我有一个函数,我想用用户选择的类对象做一些事情。我在想,我给他们一些选项,然后在他们选择它之后,我使用字符串来标识对象数组中的类对象,如下所示:

    function askAboutIt() {
  var questions = [{
    type: 'list',
    name: 'theList',
    message: "Message",
    choices: listArray
  }]

  inquirer.prompt(questions).then(answers => {
  var itemInQuestion = (answers['theList']);

   function isPicked(item) { 
    return item.name === itemInQuestion;
}

  var picked = (listArray.find(isPicked)); 
  })

}

基本上在其他一些函数内部,我希望能够调用askAboutIt() 并让它返回picked。这样我就可以,例如,console.log(askAboutIt()), 或者创建一个等于 askAboutIt().someOtherPropertyofmyListArrayClass. 的变量

我尝试在我的查询器函数中添加一个return,但它返回为未定义,所以我想,也许我可以在我的console.log 之外添加一个await,但这也没有得到回报。

然后我尝试使用 this answer 中的 when 方法,但随后我收到了一个错误,即“何时是意外标识符”。我到底应该把when 方法放在哪里,还是应该完全使用其他方法?

【问题讨论】:

  • 你有没有尝试过你心中的任何想法?这个网站更多是为了解决具体问题,而不仅仅是为人们编写代码。
  • 好点,让我用我失败的代码想法进行编辑。

标签: javascript node.js inquirer inquirerjs


【解决方案1】:

我想通了!我能够通过颠倒我的策略来做到这一点。我没有在另一个函数中调用askAboutIt(),而是编写了另一个函数parentFunction(answer),并为其提供了参数answer

然后,在askAboutIt 内部,我调用了 that 函数,如下所示:

 function askAboutIt() {
  var questions = [{
    type: 'list',
    name: 'theList',
    message: "Message",
    choices: listArray
  }]

  inquirer.prompt(questions).then(answers => {
  var itemInQuestion = (answers['theList']);

   function isPicked(item) { 
    return item.name === itemInQuestion;
}

  var picked = (listArray.find(isPicked)); 
  parentFunction(picked);
  })

}

这样,我可以在另一个函数中使用这个问题的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多