]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/rules/no-async-promise-executor.md
import 8.41.0 source
[pve-eslint.git] / eslint / docs / src / rules / no-async-promise-executor.md
1 ---
2 title: no-async-promise-executor
3 rule_type: problem
4 ---
5
6
7
8 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:
9
10 ```js
11 const result = new Promise(function executor(resolve, reject) {
12 readFile('foo.txt', function(err, result) {
13 if (err) {
14 reject(err);
15 } else {
16 resolve(result);
17 }
18 });
19 });
20 ```
21
22 The executor function can also be an `async function`. However, this is usually a mistake, for a few reasons:
23
24 * 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.
25 * 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.
26
27 ## Rule Details
28
29 This rule aims to disallow async Promise executor functions.
30
31 Examples of **incorrect** code for this rule:
32
33 ::: incorrect
34
35 ```js
36 const foo = new Promise(async (resolve, reject) => {
37 readFile('foo.txt', function(err, result) {
38 if (err) {
39 reject(err);
40 } else {
41 resolve(result);
42 }
43 });
44 });
45
46 const result = new Promise(async (resolve, reject) => {
47 resolve(await foo);
48 });
49 ```
50
51 :::
52
53 Examples of **correct** code for this rule:
54
55 ::: correct
56
57 ```js
58 const foo = new Promise((resolve, reject) => {
59 readFile('foo.txt', function(err, result) {
60 if (err) {
61 reject(err);
62 } else {
63 resolve(result);
64 }
65 });
66 });
67
68 const result = Promise.resolve(foo);
69 ```
70
71 :::
72
73 ## When Not To Use It
74
75 If your codebase doesn't support async function syntax, there's no need to enable this rule.