Are there any issues with using async
/ await
in a forEach
loop?
(在forEach
循环中使用async
/ await
是否有任何问题?)
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 useasync
/ await
in a higher order function like this, so I just wanted to ask if there was any issue with this. (我让某人告诉我,您不应该在这样的高阶函数中使用async
/ await
,所以我只想问一下这是否有问题。)