2017-06-15 273 views
1

我使用问询&打字稿2.3控制台应用程序的ReadLine(询问者)的问题循环,这里是什么goind下来异步/等待与

  • 我想有用户使用等待列表中选择一个名字。没问题
  • 之后,我希望用户选择一个或多个他想调整的选项。没问题
  • 我想循环槽所有选择的选项,使用相同的async/await像以前一样。
  • 我想填补answers对象像{fieldName: chosenOption, fieldname2: chosenOption2}

但是这就是我惹上麻烦。我已经尝试了各种选择,但是无论我使用什么样的循环,我都会得到所有* qeuestions来回答并让它们具有相同的值。

我看到这是一个广泛解释的主题,但我简单地忽略了一些明显的东西。为了不占用空间,将this.ask类属性作为要点列入。

async startInteractive() { 
    let names = Object.keys(this.config('connect')); 
    let name = await this.ask.list('name', names); 
    console.log('need to edit ', name); 
    let availableFields  = [ 'user', 'host', 'port', 'method', 'localPath', 'hostPath' ] 
    let chosenFields: Answers = await this.ask.checkbox('Choose fields to edit', availableFields) 
    let current    = this.config('connect.' + name); 

    let answers = {} 

    // THIS PART 
    // is the issue i'm not able to tackle 
    await chosenFields.map(async (field) => { 
     answers[ field ] = await this.ask.ask(field) 
    }) 
} 

编辑:这是问题的可视化表示:

  • enter image asdfasdfenter code here here
  • enter image description here
  • enter image description here
  • enter image description here
+2

避免['Promise'构造反模式](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-如何避免 - 它)在你的'InputHelper'方法(所有这些)! – Bergi

回答

1

chosenFields.map将返回一个回调结果数组,即在async回调情况下的承诺。为了能够await承诺的一个数组,你需要前使用Promise.all将其转换成一个承诺为数组:

await Promise.all(chosenFields.map(async (field) => { 
    answers[ field ] = await this.ask.ask(field) 
})) 

我不能告诉你为什么会得到相同的结果所有领域,但。当inquirer.prompt同时被调用时,似乎有一个竞争条件。连续地调用它,使用

for (let field of chosenFields) { 
    answers[ field ] = await this.ask.ask(field) 
} 
+0

必须确实调用它。非常感谢。我会去阅读Promise的构造函数antripatern。非常感谢! –