问题描述
当然代码确实可以工作,但我很确定它没有按照您的预期做。它只是触发多个异步调用,但该printFiles
函数在此之后立即返回。
按顺序阅读
如果要按顺序读取文件,确实只需使用现代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);
}
}
并行阅读
如果要并行读取文件,确实每个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)
}));
}
解决方法
在循环中使用async
/有什么问题吗?我正在尝试遍历文件数组和每个文件的内容。await``forEach``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