Skip to content

Commit 43a09b4

Browse files
authored
docs(array-foreach): add async refactor example
1 parent 15fb2b4 commit 43a09b4

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

docs/rules/array-foreach.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,35 @@ We know this code can only possibly mutate `apple`, as the return value is disca
6868

6969
While `forEach` provides a set of arguments to the callback, it is still overall _less flexible_ than a `for` loop. A `for` loop can conditionally call the callback, can pass additional arguments to the callback (which would otherwise need to be hoisted or curried), can opt to change the `receiver` (`this` value) or not pass any `receiver` at all. This extra flexibility is the reason we almost always prefer to use `for` loops over any of the Array iteration methods.
7070

71+
A good example of how `for` loops provide flexibility, where `forEach` constrains it, is to see how an iteration would be refactored to handle async work. Consider the following...
72+
73+
```js
74+
apples.forEach(polishApple)
75+
// vs...
76+
for (const apple of apples) {
77+
polishApple(apple)
78+
}
79+
```
80+
81+
If `polishApple` need to do some async work, then we'd need to refactor the iteration steps to accomodate for this async work, by `await`ing each call to `polishApple`. We cannot simply pass an `async` function to `forEach`, as it does not understand async functions, instead we'd have to turn the `forEach` into a `map` and combine that with a `Promise.all`. For example:
82+
83+
```diff
84+
- apples.forEach(polishApple)
85+
+ await Promise.all(
86+
+ apples.map(async apple => await polishApple(apple))
87+
+ )
88+
```
89+
90+
Compare this to the `for` loop, which has a much simpler path to refactoring:
91+
92+
```diff
93+
for (const apple of apples) {
94+
- polishApple(apple)
95+
+ await polishApple(apple)
96+
}
97+
```
98+
99+
71100
## See Also
72101

73102
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

0 commit comments

Comments
 (0)