Sure the code does work, but I'm pretty sure it doesn't do what you expect it to do.
(确保代码确实有效,但是我很确定它不会实现您期望的功能。)
It just fires off multiple asynchronous calls, but the printFiles
function does immediately return after that. (它只是触发多个异步调用,但是在printFiles
之后printFiles
函数确实会立即返回。)
If you want to read the files in sequence, you cannot use forEach
indeed.
(如果forEach
顺序读取文件, 则实际上不能使用forEach
。)
Just use a modern for … of
loop instead, in which await
will work as expected: (只需使用现代的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);
}
}
If you want to read the files in parallel, you cannot use forEach
indeed.
(如果要并行读取文件, 则实际上不能使用forEach
。)
Each of the async
callback function calls does return a promise, but you're throwing them away instead of awaiting them. (每个async
回调函数调用的确会返回一个Promise,但是您将它们扔掉了,而不是等待它们。)
Just use map
instead, and you can await the array of promises that you'll get with Promise.all
: (只需使用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)
}));
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…