2017-06-15 276 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。非常感謝! –