]> git.proxmox.com Git - pve-eslint.git/blame - eslint/docs/src/rules/require-await.md
import 8.41.0 source
[pve-eslint.git] / eslint / docs / src / rules / require-await.md
CommitLineData
8f9d1d4d
DC
1---
2title: require-await
8f9d1d4d
DC
3rule_type: suggestion
4related_rules:
5- require-yield
6---
7
eb39fafa
DC
8
9Asynchronous functions in JavaScript behave differently than other functions in two important ways:
10
111. The return value is always a `Promise`.
122. You can use the `await` operator inside of them.
13
14The primary reason to use asynchronous functions is typically to use the `await` operator, such as this:
15
16```js
17async function fetchData(processDataItem) {
18 const response = await fetch(DATA_URL);
19 const data = await response.json();
20
21 return data.map(processDataItem);
22}
23```
24
25Asynchronous functions that don't use `await` might not need to be asynchronous functions and could be the unintentional result of refactoring.
26
27Note: 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.
28
29## Rule Details
30
31This rule warns async functions which have no `await` expression.
32
33Examples of **incorrect** code for this rule:
34
8f9d1d4d
DC
35::: incorrect
36
eb39fafa
DC
37```js
38/*eslint require-await: "error"*/
39
40async function foo() {
41 doSomething();
42}
43
44bar(async () => {
45 doSomething();
46});
47```
48
8f9d1d4d
DC
49:::
50
eb39fafa
DC
51Examples of **correct** code for this rule:
52
8f9d1d4d
DC
53::: correct
54
eb39fafa
DC
55```js
56/*eslint require-await: "error"*/
57
58async function foo() {
59 await doSomething();
60}
61
62bar(async () => {
63 await doSomething();
64});
65
66function foo() {
67 doSomething();
68}
69
70bar(() => {
71 doSomething();
72});
73
74// Allow empty functions.
75async function noop() {}
76```
77
8f9d1d4d
DC
78:::
79
eb39fafa
DC
80## When Not To Use It
81
82Asynchronous 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:
83
84```js
85async function fail() {
86 throw new Error("Failure!");
87}
88
89fail().catch(error => {
90 console.log(error.message);
91});
92```
93
94In 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.
95
96If you are throwing an error inside of an asynchronous function for this purpose, then you may want to disable this rule.