]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/rules/no-promise-executor-return.md
95283d7b7018093756d331c7d56b7469ecb749d2
[pve-eslint.git] / eslint / docs / src / rules / no-promise-executor-return.md
1 ---
2 title: no-promise-executor-return
3 layout: doc
4 rule_type: problem
5 related_rules:
6 - no-async-promise-executor
7 further_reading:
8 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
9 ---
10
11
12 The `new Promise` constructor accepts a single argument, called an *executor*.
13
14 ```js
15 const myPromise = new Promise(function executor(resolve, reject) {
16 readFile('foo.txt', function(err, result) {
17 if (err) {
18 reject(err);
19 } else {
20 resolve(result);
21 }
22 });
23 });
24 ```
25
26 The executor function usually initiates some asynchronous operation. Once it is finished, the executor should call `resolve` with the result, or `reject` if an error occurred.
27
28 The return value of the executor is ignored. Returning a value from an executor function is a possible error because the returned value cannot be used and it doesn't affect the promise in any way.
29
30 ## Rule Details
31
32 This rule disallows returning values from Promise executor functions.
33
34 Only `return` without a value is allowed, as it's a control flow statement.
35
36 Examples of **incorrect** code for this rule:
37
38 ::: incorrect
39
40 ```js
41 /*eslint no-promise-executor-return: "error"*/
42
43 new Promise((resolve, reject) => {
44 if (someCondition) {
45 return defaultResult;
46 }
47 getSomething((err, result) => {
48 if (err) {
49 reject(err);
50 } else {
51 resolve(result);
52 }
53 });
54 });
55
56 new Promise((resolve, reject) => getSomething((err, data) => {
57 if (err) {
58 reject(err);
59 } else {
60 resolve(data);
61 }
62 }));
63
64 new Promise(() => {
65 return 1;
66 });
67 ```
68
69 :::
70
71 Examples of **correct** code for this rule:
72
73 ::: correct
74
75 ```js
76 /*eslint no-promise-executor-return: "error"*/
77
78 new Promise((resolve, reject) => {
79 if (someCondition) {
80 resolve(defaultResult);
81 return;
82 }
83 getSomething((err, result) => {
84 if (err) {
85 reject(err);
86 } else {
87 resolve(result);
88 }
89 });
90 });
91
92 new Promise((resolve, reject) => {
93 getSomething((err, data) => {
94 if (err) {
95 reject(err);
96 } else {
97 resolve(data);
98 }
99 });
100 });
101
102 Promise.resolve(1);
103 ```
104
105 :::