index.js
1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
'use strict';
class CancelError extends Error {
constructor(reason) {
super(reason || 'Promise was canceled');
this.name = 'CancelError';
}
get isCanceled() {
return true;
}
}
class PCancelable {
static fn(userFn) {
return (...args) => {
return new PCancelable((resolve, reject, onCancel) => {
args.push(onCancel);
userFn(...args).then(resolve, reject);
});
};
}
constructor(executor) {
this._cancelHandlers = [];
this._isPending = true;
this._isCanceled = false;
this._rejectOnCancel = true;
this._promise = new Promise((resolve, reject) => {
this._reject = reject;
const onResolve = value => {
this._isPending = false;
resolve(value);
};
const onReject = error => {
this._isPending = false;
reject(error);
};
const onCancel = handler => {
this._cancelHandlers.push(handler);
};
Object.defineProperties(onCancel, {
shouldReject: {
get: () => this._rejectOnCancel,
set: bool => {
this._rejectOnCancel = bool;
}
}
});
return executor(onResolve, onReject, onCancel);
});
}
then(onFulfilled, onRejected) {
return this._promise.then(onFulfilled, onRejected);
}
catch(onRejected) {
return this._promise.catch(onRejected);
}
finally(onFinally) {
return this._promise.finally(onFinally);
}
cancel(reason) {
if (!this._isPending || this._isCanceled) {
return;
}
if (this._cancelHandlers.length > 0) {
try {
for (const handler of this._cancelHandlers) {
handler();
}
} catch (error) {
this._reject(error);
}
}
this._isCanceled = true;
if (this._rejectOnCancel) {
this._reject(new CancelError(reason));
}
}
get isCanceled() {
return this._isCanceled;
}
}
Object.setPrototypeOf(PCancelable.prototype, Promise.prototype);
module.exports = PCancelable;
module.exports.default = PCancelable;
module.exports.CancelError = CancelError;