]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/no-await-in-loop.md
first commit
[pve-eslint.git] / eslint / docs / rules / no-await-in-loop.md
1 # Disallow `await` inside of loops (no-await-in-loop)
2
3 Performing an operation on each element of an iterable is a common task. However, performing an
4 `await` as part of each operation is an indication that the program is not taking full advantage of
5 the parallelization benefits of `async`/`await`.
6
7 Usually, the code should be refactored to create all the promises at once, then get access to the
8 results using `Promise.all()`. Otherwise, each successive operation will not start until the
9 previous one has completed.
10
11 Concretely, the following function should be refactored as shown:
12
13 ```js
14 async function foo(things) {
15 const results = [];
16 for (const thing of things) {
17 // Bad: each loop iteration is delayed until the entire asynchronous operation completes
18 results.push(await bar(thing));
19 }
20 return baz(results);
21 }
22 ```
23
24 ```js
25 async function foo(things) {
26 const results = [];
27 for (const thing of things) {
28 // Good: all asynchronous operations are immediately started.
29 results.push(bar(thing));
30 }
31 // Now that all the asynchronous operations are running, here we wait until they all complete.
32 return baz(await Promise.all(results));
33 }
34 ```
35
36 ## Rule Details
37
38 This rule disallows the use of `await` within loop bodies.
39
40 ## Examples
41
42 Examples of **correct** code for this rule:
43
44 ```js
45 async function foo(things) {
46 const results = [];
47 for (const thing of things) {
48 // Good: all asynchronous operations are immediately started.
49 results.push(bar(thing));
50 }
51 // Now that all the asynchronous operations are running, here we wait until they all complete.
52 return baz(await Promise.all(results));
53 }
54 ```
55
56 Examples of **incorrect** code for this rule:
57
58 ```js
59 async function foo(things) {
60 const results = [];
61 for (const thing of things) {
62 // Bad: each loop iteration is delayed until the entire asynchronous operation completes
63 results.push(await bar(thing));
64 }
65 return baz(results);
66 }
67 ```
68
69 ## When Not To Use It
70
71 In many cases the iterations of a loop are not actually independent of each-other. For example, the
72 output of one iteration might be used as the input to another. Or, loops may be used to retry
73 asynchronous operations that were unsuccessful. Or, loops may be used to prevent your code from sending
74 an excessive amount of requests in parallel. In such cases it makes sense to use `await` within a
75 loop and it is recommended to disable the rule via a standard ESLint disable comment.