在 forEach
循环中使用 async
/await
是否存在任何问题?我正在尝试循环遍历文件数组并 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()
这段代码确实有效,但是会出现什么问题吗?有人告诉我你不应该在这样的高阶函数中使用 async
/await
,所以我只是想问是否有任何问题有了这个。
最佳答案
当然,代码确实有效,但我很确定它没有达到您期望的效果。它只是触发多个异步调用,但 printFiles
函数会立即返回。
按顺序阅读
如果你想按顺序读取文件,你确实不能使用forEach
。只需使用现代的 for … of
循环即可,其中 await
将按预期工作:
async function printFiles () {
const files = await getFilePaths();
for (const file of files) {
const contents = await fs.readFile(file, 'utf8');
console.log(contents);
}
}
并行读取
如果你想并行读取文件,你确实不能使用forEach
。每个async
回调函数调用都会返回一个promise,但是您将它们扔掉而不是等待它们。只需使用 map
来代替,您就可以等待通过 Promise.all
获得的 promise 数组:
async function printFiles () {
const files = await getFilePaths();
await Promise.all(files.map(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
}));
}
关于javascript - 将 async/await 与 forEach 循环结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53241758/