Proposed rule: no-await-in-loop
See original GitHub issueWhen does this rule warn?
This rule warns when a developer uses await
inside of a loop. Doing so means that each loop iteration will run in serial, when often the desired behavior is to dispatch a bunch of asynchronous operations and then await on the result as a whole, using Promise.all
.
Occasionally, awaiting inside a loop actually is desirable. In cases like those,
Here is an example:
async foo() {
for (const bar of baz) {
await(bar);
}
}
Here is my proposed warning:
‘Avoid using await inside a loop. Consider refactoring to use Promise.all. If you are sure you want to do this, add // eslint-disable-line no-await-in-loop
at the end of this line.’
Is this rule preventing an error or is it stylistic?
This rule prevents an error. Needlessly awaiting inside of a loop can have serious performance implications.
Why is this rule a candidate for inclusion instead of creating a custom rule?
Using await
inside of a loop is a bad pattern no matter what codebase you are operating in. There are occasional places where it is desirable but it is almost always a sign that you have done something wrong.
My only concern is that this rule will not operate with the eslint
frontend – to my knowledge, it has not implemented async/await parsing yet. Therefore it could be confusing to have a rule built-in to eslint
that requires its users to use babel-eslint
.
Are you willing to create the rule yourself?
Yes. I have already written the first version.
Issue Analytics
- State:
- Created 8 years ago
- Reactions:6
- Comments:19 (18 by maintainers)
@nmote This issue is now accepted - let us know if you have any issues and thanks for being willing to work on this!
Sorry for holding this up. I’m still not a huge fan of relying on the built in
eslint-disable
comments (rather than a rule-specific thing), but given that’s my only concern, I support this rule. We can always add a rule-specific way to disable if it feels necessary in the future.