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