-
Notifications
You must be signed in to change notification settings - Fork 63
Closed
Description
About this example:
eslint-plugin-github/docs/rules/array-foreach.md
Lines 83 to 100 in a8ec7ad
| 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: | |
| ```diff | |
| - apples.forEach(polishApple) | |
| + await Promise.all( | |
| + apples.map(polishApple) | |
| + ) | |
| ``` | |
| Compare this to the `for` loop, which has a much simpler path to refactoring: | |
| ```diff | |
| for (const apple of apples) { | |
| - polishApple(apple) | |
| + await polishApple(apple) | |
| } | |
| ``` | |
The following code creates N async promises in parallel and wait until they are all completed (it polishes all apples at the same time until they are all polished):
await Promise.all(
apples.map(polishApple)
) The following code awaits for each async call individually (it polishes 1 apple at time until they are all polished).
for (const apple of apples) {
await polishApple(apple)
} This is a refactor changing substantially the behaviour of the code.
Metadata
Metadata
Assignees
Labels
No labels