在 forEach
循环中使用 async
/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
代替,您就可以 await 通过 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/58085871/