在 forEach 循环中使用 async/await
问题:
在循环中使用async/有什么问题吗?我正在尝试遍历文件数组和每个文件的内容。
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:
async function printFiles () {
const files = await getFilePaths();
await Promise.all(files.map(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
}));
}本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!