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