Skip to content

Commit

Permalink
eslint: Disable no-await-in-loop.
Browse files Browse the repository at this point in the history
The docs at https://eslint.org/docs/rules/no-await-in-loop say,
"Usually, the code should be refactored to create all the promises
then get access to the results using `Promise.all()`. Otherwise, each
successive operation will not start until the previous one has
completed."

But sometimes invoking one asynchronous task depends on the
resolution of the previous task, or it's important to have only one
task in progress at a time. If either of these is important, the
programmer must use an `eslint-disable` within their `for` or
`while` loop.

The only other choice that seems reasonable is to use
Array.prototype.forEach, but this will introduce a bug: A promise
returned by the callback passed to forEach is not `await`ed before
the next invocation of the callback.

['a', 'b', 'c'].forEach(async letter => {
  await new Promise(resolve => setTimeout(resolve, 1000));
  console.log(letter);
});

The desired result is

// (one second passes)
// 'a'
// (one second passes)
// 'b'
// (one second passes)
// 'c'

but the actual result is

// (one second passes)
// 'a'
// 'b'
// 'c'

With this rule, if you want to `await` sequentially in a loop, you
have to choose between an `eslint-disable` and the failure of using
a forEach. It's reasonable to assume that someone will choose wrong
because they trust our choice of rules and they're not looking
closely at the implementation of forEach. So, we're better without
it.
  • Loading branch information
Chris Bobbe authored and rk-for-zulip committed Apr 10, 2020
1 parent daab817 commit 4fcfb76
Showing 1 changed file with 2 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .eslintrc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ rules:
# Formatting and naming
camelcase: off

no-await-in-loop: off # Promise.all is not always desirable

# Permit dangling underscores in class property names, to denote "private"
# fields. (These should be replaced with true private fields per the TC39
# class fields proposal [1], once that's available to us.)
Expand Down

0 comments on commit 4fcfb76

Please sign in to comment.