@trenskow/custom-promise 0.10.3 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +19 -18
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -4,19 +4,19 @@ class CustomPromise {
4
4
 
5
5
  constructor() {
6
6
  this._state = 'pending';
7
- this._awaiters = [];
7
+ this._result = undefined;
8
8
  this._finalizers = [];
9
- }
10
-
11
- _reset() {
12
- this._state = 'pending';
9
+ this._onFulfilled = [];
10
+ this._onRejected = [];
13
11
  }
14
12
 
15
13
  _resolve(result) {
16
14
  if (this._state !== 'pending') return;
17
15
  this._state = 'fulfilled';
18
16
  this._result = result;
19
- this._awaiters.splice(0).forEach(([onFulfilled]) => onFulfilled(result));
17
+ this._onFulfilled
18
+ .filter((onFulfilled) => typeof onFulfilled === 'function')
19
+ .forEach((onFulfilled) => onFulfilled(result));
20
20
  this._finalizers.splice(0).forEach((onFinally) => onFinally());
21
21
  }
22
22
 
@@ -24,25 +24,25 @@ class CustomPromise {
24
24
  if (this._state !== 'pending') return;
25
25
  this._state = 'rejected';
26
26
  this._error = error;
27
- this._awaiters.splice(0).forEach(([, onRejected]) => onRejected(error));
27
+ this._onRejected
28
+ .filter((onRejected) => typeof onRejected === 'function')
29
+ .forEach((onRejected) => onRejected(error));
28
30
  this._finalizers.splice(0).forEach((onFinally) => onFinally());
29
31
  }
30
32
 
31
33
  then(onFulfilled, onRejected) {
32
34
 
33
- if (onFulfilled && typeof onFulfilled !== 'function') throw new TypeError('fulfilled must be a function.');
34
- if (onRejected && typeof onRejected !== 'function') throw new TypeError('rejected must be a function.');
35
-
36
35
  if (this._state === 'fulfilled') {
37
- if (onFulfilled) onFulfilled(this._result);
38
- }
39
- else if (this._state === 'rejected') {
40
- if (onRejected) onRejected(this._error);
36
+ onFulfilled?.(this._result);
37
+ } else if (this._state === 'rejected') {
38
+ onRejected?.(this._error);
39
+ } else {
40
+ this._onFulfilled.push(onFulfilled);
41
+ this._onRejected.push(onRejected);
41
42
  }
42
- else {
43
- this._awaiters.push([onFulfilled, onRejected]);
44
- }
45
-
43
+
44
+ return this;
45
+
46
46
  }
47
47
 
48
48
  finally(onFinally) {
@@ -50,6 +50,7 @@ class CustomPromise {
50
50
  else {
51
51
  this._finalizers.push(onFinally);
52
52
  }
53
+ return this;
53
54
  }
54
55
 
55
56
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trenskow/custom-promise",
3
- "version": "0.10.3",
3
+ "version": "0.12.0",
4
4
  "description": "A extendable class for making custom promises.",
5
5
  "main": "index.js",
6
6
  "directories": {