xxxxxxxxxx
async function printFiles () {
const files = await getFilePaths();
for (const file of files) {
const contents = await fs.readFile(file, 'utf8');
console.log(contents);
}
}
xxxxxxxxxx
// 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);
}))
xxxxxxxxxx
async function printFiles () {
const files = await getFilePaths();
await Promise.all(files.map(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
}));
}
xxxxxxxxxx
const players = await this.getWinners();
// BAD
await players.forEach(async (player) => {
await givePrizeToPlayer(player);
});
await sendEmailToAdmin('All prizes awarded');
============================
Ideal way is
for (const player of players) {
await givePrizeToPlayer(player);
}
xxxxxxxxxx
const players = await this.getWinners();
// BAD
await players.forEach(async (player) => {
await givePrizeToPlayer(player);
});
await sendEmailToAdmin('All prizes awarded');
xxxxxxxxxx
for await (const results of array) {
await longRunningTask()
}
console.log('I will wait')
xxxxxxxxxx
const players = await this.getWinners();
// BAD
await players.forEach(async (player) => {
await givePrizeToPlayer(player);
});
await sendEmailToAdmin('All prizes awarded');
xxxxxxxxxx
const players = await this.getWinners();
// BAD
await players.forEach(async (player) => {
await givePrizeToPlayer(player);
});
await sendEmailToAdmin('All prizes awarded');
xxxxxxxxxx
files.forEach(async (file) => {
const contents = await fs.readFile(file, 'utf8')
})
xxxxxxxxxx
const players = await this.getWinners();
// BAD
await players.forEach(async (player) => {
await givePrizeToPlayer(player);
});
await sendEmailToAdmin('All prizes awarded');