]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/rules/no-async-promise-executor.md
4c6a85414d9ecea5bb9d391d307a2e9d7563910f
[pve-eslint.git] / eslint / docs / src / rules / no-async-promise-executor.md
1 ---
2 title: no-async-promise-executor
3 layout: doc
4 rule_type: problem
5 ---
6
7
8
9 The `new Promise` constructor accepts an *executor* function as an argument, which has `resolve` and `reject` parameters that can be used to control the state of the created Promise. For example:
10
11 ```js
12 const result = new Promise(function executor(resolve, reject) {
13 readFile('foo.txt', function(err, result) {
14 if (err) {
15 reject(err);
16 } else {
17 resolve(result);
18 }
19 });
20 });
21 ```
22
23 The executor function can also be an `async function`. However, this is usually a mistake, for a few reasons:
24
25 * If an async executor function throws an error, the error will be lost and won't cause the newly-constructed `Promise` to reject. This could make it difficult to debug and handle some errors.
26 * If a Promise executor function is using `await`, this is usually a sign that it is not actually necessary to use the `new Promise` constructor, or the scope of the `new Promise` constructor can be reduced.
27
28 ## Rule Details
29
30 This rule aims to disallow async Promise executor functions.
31
32 Examples of **incorrect** code for this rule:
33
34 ::: incorrect
35
36 ```js
37 const foo = new Promise(async (resolve, reject) => {
38 readFile('foo.txt', function(err, result) {
39 if (err) {
40 reject(err);
41 } else {
42 resolve(result);
43 }
44 });
45 });
46
47 const result = new Promise(async (resolve, reject) => {
48 resolve(await foo);
49 });
50 ```
51
52 :::
53
54 Examples of **correct** code for this rule:
55
56 ::: correct
57
58 ```js
59 const foo = new Promise((resolve, reject) => {
60 readFile('foo.txt', function(err, result) {
61 if (err) {
62 reject(err);
63 } else {
64 resolve(result);
65 }
66 });
67 });
68
69 const result = Promise.resolve(foo);
70 ```
71
72 :::
73
74 ## When Not To Use It
75
76 If your codebase doesn't support async function syntax, there's no need to enable this rule.