gpt4 book ai didi

typescript - 带有 readline(询问者)问题的异步/等待循环

转载 作者:搜寻专家 更新时间:2023-10-30 21:51:03 30 4
gpt4 key购买 nike

我正在为控制台应用程序使用 Inquirer 和 Typescript 2.3,这是发生了什么事

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

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

我看到这是一个被广泛解释的主题,但我只是忽略了一些显而易见的事情。为了不占空间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

最佳答案

chosenFields.map 将返回一组回调结果,即 async 回调的 promise 。为了能够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)
}

关于typescript - 带有 readline(询问者)问题的异步/等待循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44564544/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com