@trenskow/custom-promise 0.9.1 → 0.10.2

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.
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "cSpell.words": [
3
- "readline"
3
+ "finalizers"
4
4
  ]
5
- }
5
+ }
package/index.js CHANGED
@@ -5,39 +5,53 @@ class CustomPromise {
5
5
  constructor() {
6
6
  this._state = 'pending';
7
7
  this._awaiters = [];
8
+ this._finalizers = [];
9
+ }
10
+
11
+ _reset() {
12
+ this._state = 'pending';
8
13
  }
9
14
 
10
15
  _resolve(result) {
11
16
  if (this._state !== 'pending') return;
12
17
  this._state = 'fulfilled';
13
18
  this._result = result;
14
- this._awaiters.splice(0).forEach(([fulfilled]) => fulfilled(result));
19
+ this._awaiters.splice(0).forEach(([onFulfilled]) => onFulfilled(result));
20
+ this._finalizers.splice(0).forEach((onFinally) => onFinally());
15
21
  }
16
22
 
17
23
  _reject(error) {
18
24
  if (this._state !== 'pending') return;
19
25
  this._state = 'rejected';
20
26
  this._error = error;
21
- this._awaiters.splice(0).forEach(([, rejected]) => rejected(error));
27
+ this._awaiters.splice(0).forEach(([, onRejected]) => onRejected(error));
28
+ this._finalizers.splice(0).forEach((onFinally) => onFinally());
22
29
  }
23
30
 
24
- then(fulfilled, rejected) {
31
+ then(onFulfilled, onRejected) {
25
32
 
26
- if (fulfilled && typeof fulfilled !== 'function') throw new TypeError('fulfilled must be a function.');
27
- if (rejected && typeof rejected !== 'function') throw new TypeError('rejected must be a function.');
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.');
28
35
 
29
36
  if (this._state === 'fulfilled') {
30
- if (fulfilled) fulfilled(this._result);
37
+ if (onFulfilled) onFulfilled(this._result);
31
38
  }
32
39
  else if (this._state === 'rejected') {
33
- if (rejected) rejected(this._error);
40
+ if (onRejected) onRejected(this._error);
34
41
  }
35
42
  else {
36
- this._awaiters.push([fulfilled, rejected]);
43
+ this._awaiters.push([onFulfilled, onRejected]);
37
44
  }
38
45
 
39
46
  }
40
47
 
48
+ finally(onFinally) {
49
+ if (this._state !== 'pending') onFinally();
50
+ else {
51
+ this._finalizers.push(onFinally);
52
+ }
53
+ }
54
+
41
55
  }
42
56
 
43
57
  exports = module.exports = CustomPromise;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trenskow/custom-promise",
3
- "version": "0.9.1",
3
+ "version": "0.10.2",
4
4
  "description": "A extendable class for making custom promises.",
5
5
  "main": "index.js",
6
6
  "directories": {