Skip to content

Conversation

@Hweinstock
Copy link
Contributor

Problem

forEach can lead to race conditions with async methods, and is often used instead of map, find, some, reduce, flatMap, etc...

Solution

Add a lint rule for forEach and migrate away from it.


  • Treat all work as PUBLIC. Private feature/x branches will not be squash-merged at release time.
  • Your code changes must meet the guidelines in CONTRIBUTING.md.
  • License: I confirm that my contribution is made under the terms of the Apache 2.0 license.

'aws-toolkits/no-console-log': 'error',
'aws-toolkits/no-json-stringify-in-log': 'error',
'aws-toolkits/no-printf-mismatch': 'error',
'aws-toolkits/no-foreach': 'error',
Copy link
Contributor

@justinmk3 justinmk3 Dec 19, 2024

Choose a reason for hiding this comment

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

We depend on eslint-plugin-unicorn so I think we can use this rule: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-array-for-each.md

in .eslintrc.js where we enable the rule, let's put a comment like:

// Discourage `.forEach` because it can lead to accidental, incorrect use of async callbacks.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Good idea! That rule also comes with a way to auto-fix most cases so I switched over to it completely here: #6281

const requestId = resp.$response.requestId
logStr += `\n${indent('RequestID: ', 4)}${requestId},\n${indent('Customizations:', 4)}`
resp.customizations.forEach((c, index) => {
for (const [c, index] of enumerate(resp.customizations)) {
Copy link
Contributor

@justinmk3 justinmk3 Dec 19, 2024

Choose a reason for hiding this comment

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

Does using enumerate() mean we are iterating the collection twice? Does this work instead:

for (const [index, element] of array.entries()) {

@Hweinstock
Copy link
Contributor Author

Moved to #6281

@Hweinstock Hweinstock closed this Dec 20, 2024
@Hweinstock Hweinstock deleted the noForEach branch December 20, 2024 18:27
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.

2 participants