// Array.prototype.forEach is not designed for asynchronous code.
// Instead use await Promise.all to process all in parallel if the order doesn't matter.
await Promise.all(array.map(async (element) => {
await someFunction(element);
}))
async function printFiles () {
const files = await getFilePaths();
await Promise.all(files.map(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
}));
}
for (const file of files) {
const contents = await fs.readFile(file, 'utf8');
console.log(contents);
}
export async function asyncForEach<T>(array: Array<T>, callback: (item: T, index: number) => void) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index);
}
}
await asyncForEach(receipts, async (eachItem) => {
await ...
})
// Javascript will proceed to call the code that comes AFTER the forEach loop,
// and then execute the code within the loop. This is because forEach is not
// async-aware. YOU CANNOT USE AWAIT IN FOREACH. Use a regular for loop instead.