确保代码确实有效,但是我很确定它不会实现您期望的功能。它只会触发多个异步调用,但
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) }));}


