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