forEach Javascript - STOP USING IT! for Async Await Code | forEach vs for...of

preview_player
Показать описание
Should you stop using forEach? Learn how forEach works and when to use it. Also learn how the for...of loop works and when to use it.

React Native Expo videos:

Flutter Videos:

FingoBox Videos:
Рекомендации по теме
Комментарии
Автор

but you didn't explain why the forEach loop behaved that way... why does the all the addtion parts get called first before the substration parts?

sangwookim
Автор

It has nothing to do with forEach vs for...of way of iteration. It's only caused by the fact that in forEach you used async calls and in for...of you called everything synchronously.

If you run forEach like that:
numbers.forEach((e, i) => {
const addAnswer = add(e, e);
console.log("addAnswer: ", addAnswer);

const subtractAnswer = subtract(e + i, e);
console.log("subtractAnswer: ", subtractAnswer);
})
you'll get exactly what you expected.

If your goal is to control the order of function execution, you don't want to use async/await. As you did in for...of example.

myPrzeslaw