【问题标题】:async/wait loop with readline (inquirer) questions带有 readline (inquirer) 问题的异步/等待循环
【发布时间】:2017-06-15 18:26:17
【问题描述】:

我正在使用 Inquirer & Typescript 2.3 作为控制台应用程序,下面是内容

  • 我想让用户使用 await 从列表中选择一个名称。没问题
  • 之后,我希望用户选择一个或多个他想要调整的选项。没问题
  • 我想循环遍历所有选择的选项,使用与以前相同的 async/await。
  • 我想填充answers 对象,例如{fieldName: chosenOption, fieldname2: chosenOption2}

但这就是我遇到麻烦的地方。我尝试了各种选项,但无论我使用哪种循环,我最终都会得到所有 * qeuestions 来回答并让它们具有相同的值。

我看到这是一个广泛解释的主题,但我只是忽略了一些显而易见的事情。为了不占用空间,this.ask 类属性作为 gist 包含在内。

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)
    })
}

编辑:这是问题的直观表示:

【问题讨论】:

标签: typescript promise async-await


【解决方案1】:

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

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)
}

【讨论】:

  • 确实必须依次调用它。非常感谢。我也会去阅读那个 Promise 构造函数 antripatern。非常感谢!
猜你喜欢
  • 2020-04-20
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 2017-08-15
相关资源
最近更新 更多