DekGenius.com
JAVASCRIPT
async await forEach
// 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);
}))
use await in for each
files.forEach(async (file) => {
const contents = await fs.readFile(file, 'utf8')
})
async foreach
[1, 2, 3].forEach(async (num) => { await waitFor(50); console.log(num);});console.log('Done');
Do not use forEach with async-await
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);
}
Do not use forEach with async-await
const players = await this.getWinners();
// BAD
await players.forEach(async (player) => {
await givePrizeToPlayer(player);
});
await sendEmailToAdmin('All prizes awarded');
Do not use forEach with async-await
const players = await this.getWinners();
// BAD
await players.forEach(async (player) => {
await givePrizeToPlayer(player);
});
await sendEmailToAdmin('All prizes awarded');
await asyc foreach
Array.prototype.forEachAsync = async function (fn) {
for (let t of this) { await fn(t) }
}
Array.prototype.forEachAsyncParallel = async function (fn) {
await Promise.all(this.map(fn));
}
Do not use forEach with async-await
const players = await this.getWinners();
// BAD
await players.forEach(async (player) => {
await givePrizeToPlayer(player);
});
await sendEmailToAdmin('All prizes awarded');
Do not use forEach with async-await
const players = await this.getWinners();
// BAD
await players.forEach(async (player) => {
await givePrizeToPlayer(player);
});
await sendEmailToAdmin('All prizes awarded');
Do not use forEach with async-await
const players = await this.getWinners();
// BAD
await players.forEach(async (player) => {
await givePrizeToPlayer(player);
});
await sendEmailToAdmin('All prizes awarded');
Do not use forEach with async-await
const players = await this.getWinners();
// BAD
await players.forEach(async (player) => {
await givePrizeToPlayer(player);
});
await sendEmailToAdmin('All prizes awarded');
foreach async not working
async function printFiles () {
const files = await getFilePaths();
for (const file of files) {
const contents = await fs.readFile(file, 'utf8');
console.log(contents);
}
}
js await in foreach
// 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.
Do not use forEach with async-await
const players = await this.getWinners();
// BAD
await players.forEach(async (player) => {
await givePrizeToPlayer(player);
});
await sendEmailToAdmin('All prizes awarded');
© 2022 Copyright:
DekGenius.com