]> git.proxmox.com Git - pve-eslint.git/blame - 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
CommitLineData
eb39fafa
DC
1# disallow using an async function as a Promise executor (no-async-promise-executor)
2
3The `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
6const 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
17The 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
24This rule aims to disallow async Promise executor functions.
25
26Examples of **incorrect** code for this rule:
27
28```js
29const 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
39const result = new Promise(async (resolve, reject) => {
40 resolve(await foo);
41});
42```
43
44Examples of **correct** code for this rule:
45
46```js
47const 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
57const result = Promise.resolve(foo);
58```
59
60## When Not To Use It
61
62If your codebase doesn't support async function syntax, there's no need to enable this rule.