我有一个函数,其中我想使用用户选择的类对象做一些事情。我在想,我会提供一些选项,然后它们选择它后,我使用字符串在类似的对象中识别类对象:
: 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
,但这也没有得到返回。
因此,我尝试使用此答案中的when
方法,但随后我返回了一个错误,即"什么时候是意外的标识符"。我到底应该在哪里放置when
方法,还是应该完全使用其他东西?
我弄清楚了!我能够通过颠倒策略来做到这一点。我没有在另一个功能中调用askAboutIt()
,而是编写了另一个函数parentFunction(answer)
,并将其赋予了参数answer
。
然后,在askAboutIt
内,我称函数,如这样:
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);
})
}
这样,我可以在另一个功能中使用此问题的答案。