Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: describe Array#forEach anti patterns #87

Merged
merged 5 commits into from Jan 30, 2020

Conversation

keithamus
Copy link
Member

@keithamus keithamus commented Jan 29, 2020

Closes #86.

This describes in more detail why we discourage forEach, instead preferring for...of.

/cc @koddsson @zeke

@keithamus keithamus requested a review from a team January 29, 2020 15:11
@muan
Copy link
Contributor

muan commented Jan 29, 2020

I believe @zeke was also right with regards to async functions in that forEach is blocking while for...of isn't. I vaguely remember that being the reason. cc @dgraham

@dgraham
Copy link
Contributor

dgraham commented Jan 29, 2020

async function doSomething(x) { await ... }

// Probably doesn't do what you expect.
items.forEach(item => { await doSomething(item })

// vs

// Blocks the loop as expected.
for (const item of items) {
  await doSomething(item)
}

@keithamus
Copy link
Member Author

keithamus commented Jan 29, 2020

This is a syntax error:

items.forEach(item => { await doSomething(item) })

This will await, but the async function itself is not awaited because forEach does nothing with the return value:

items.forEach(async item => { await doSomething(item) })

This is how you'd have to refactor this to be async:

await Promise.all(items.map(async item => { await doSomething(item) }))

I'll add this as an example in the Flexibility heading.

docs/rules/array-foreach.md Show resolved Hide resolved
Copy link
Contributor

@zeke zeke left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wow thanks for taking the time to document this. Looks good. 👍

docs/rules/array-foreach.md Outdated Show resolved Hide resolved
docs/rules/array-foreach.md Show resolved Hide resolved
@keithamus keithamus merged commit e9e52f7 into master Jan 30, 2020
@keithamus keithamus deleted the docs-describe-array-foreach-anti-patterns branch January 30, 2020 14:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Why is forEach discouraged?
4 participants