]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/require-await.md
bump version to 8.4.0-3
[pve-eslint.git] / eslint / docs / rules / require-await.md
1 # Disallow async functions which have no `await` expression (require-await)
2
3 Asynchronous functions in JavaScript behave differently than other functions in two important ways:
4
5 1. The return value is always a `Promise`.
6 2. You can use the `await` operator inside of them.
7
8 The primary reason to use asynchronous functions is typically to use the `await` operator, such as this:
9
10 ```js
11 async function fetchData(processDataItem) {
12 const response = await fetch(DATA_URL);
13 const data = await response.json();
14
15 return data.map(processDataItem);
16 }
17 ```
18
19 Asynchronous functions that don't use `await` might not need to be asynchronous functions and could be the unintentional result of refactoring.
20
21 Note: this rule ignores async generator functions. This is because generators yield rather than return a value and async generators might yield all the values of another async generator without ever actually needing to use await.
22
23 ## Rule Details
24
25 This rule warns async functions which have no `await` expression.
26
27 Examples of **incorrect** code for this rule:
28
29 ```js
30 /*eslint require-await: "error"*/
31
32 async function foo() {
33 doSomething();
34 }
35
36 bar(async () => {
37 doSomething();
38 });
39 ```
40
41 Examples of **correct** code for this rule:
42
43 ```js
44 /*eslint require-await: "error"*/
45
46 async function foo() {
47 await doSomething();
48 }
49
50 bar(async () => {
51 await doSomething();
52 });
53
54 function foo() {
55 doSomething();
56 }
57
58 bar(() => {
59 doSomething();
60 });
61
62 // Allow empty functions.
63 async function noop() {}
64 ```
65
66 ## When Not To Use It
67
68 Asynchronous functions are designed to work with promises such that throwing an error will cause a promise's rejection handler (such as `catch()`) to be called. For example:
69
70 ```js
71 async function fail() {
72 throw new Error("Failure!");
73 }
74
75 fail().catch(error => {
76 console.log(error.message);
77 });
78 ```
79
80 In this case, the `fail()` function throws an error that is intended to be caught by the `catch()` handler assigned later. Converting the `fail()` function into a synchronous function would require the call to `fail()` to be refactored to use a `try-catch` statement instead of a promise.
81
82 If you are throwing an error inside of an asynchronous function for this purpose, then you may want to disable this rule.
83
84 ## Related Rules
85
86 * [require-yield](require-yield.md)