Skip to content

Incorrect refactor in async example #133

Closed
@jrobichaud

Description

@jrobichaud

About this example:

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions