Another issue is that using async/await inside a forEach loop, which is something we often tend to do, can lead to unintended consequences. The problem here is that forEach does not recognize async functions or handle promises correctly. Although your code may seem to "work" without throwing any errors, it won't actually await each readFile operation as intended.
Here's what happens:
The forEach loop starts all the readFile operations almost simultaneously, moving on to the next one before they finish. Since forEach doesn’t wait for the asynchronous function to complete, the printFiles function will be called before all file contents are fully read. This could cause the logs to be incomplete or lead to other issues depending on the situation.
If you need to process each file in turn, a regular for...of loop is more effective because it correctly handles await:
import fs from 'fs-promise'; async function printFiles() { const files = await getFilePaths(); // Assume this works fine for (const file of files) { const contents = await fs.readFile(file, 'utf8'); console.log(contents); } } printFiles();
This ensures that each file is read and logged before moving on to the next one.
To sum it up, avoid using async/await inside forEach, as it may not work as expected. Instead, use a for...of the loop to guarantee proper sequential execution of asynchronous functions.
for i = ...never fails.