]> git.proxmox.com Git - pve-eslint.git/blame - 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
CommitLineData
8f9d1d4d
DC
1---
2title: no-async-promise-executor
8f9d1d4d
DC
3rule_type: problem
4---
5
6
eb39fafa
DC
7
8The `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
11const 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
22The 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
29This rule aims to disallow async Promise executor functions.
30
31Examples of **incorrect** code for this rule:
32
8f9d1d4d
DC
33::: incorrect
34
eb39fafa
DC
35```js
36const 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
46const result = new Promise(async (resolve, reject) => {
47 resolve(await foo);
48});
49```
50
8f9d1d4d
DC
51:::
52
eb39fafa
DC
53Examples of **correct** code for this rule:
54
8f9d1d4d
DC
55::: correct
56
eb39fafa
DC
57```js
58const 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
68const result = Promise.resolve(foo);
69```
70
8f9d1d4d
DC
71:::
72
eb39fafa
DC
73## When Not To Use It
74
75If your codebase doesn't support async function syntax, there's no need to enable this rule.