在forEach循環中使用異步/等待 - Using async/await with a forEach loop

問題:

Are there any issues with using async / await in a forEach loop? forEach循環中使用async / await是否有任何問題? I'm trying to loop through an array of files and await on the contents of each file. 我正在嘗試遍歷文件數組並await每一個文件的內容。 數組

import fs from 'fs-promise'

async function printFiles () {
  const files = await getFilePaths() // Assume this works fine

  files.forEach(async (file) => {
    const contents = await fs.readFile(file, 'utf8')
    console.log(contents)
  })
}

printFiles()

This code does work, but could something go wrong with this? 這段代碼確實有效,可是這可能會出問題嗎? I had someone tell me that you're not supposed to use async / await in a higher order function like this, so I just wanted to ask if there was any issue with this. 我讓某人告訴我,您不該該在這樣的高階函數中使用async / await ,因此我只想問一下這是否有問題。 promise


解決方案:

參考一: https://stackoom.com/question/2XfPZ/在forEach循環中使用異步-等待
參考二: https://oldbug.net/q/2XfPZ/Using-async-await-with-a-forEach-loop
相關文章
相關標籤/搜索