-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pact.js
51 lines (49 loc) · 1.36 KB
/
Pact.js
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
const STATUS = {
PENDING: 0,
RESOLVED: 1,
REJECTED: 2,
}
class Pact {
constructor(fn) {
this.thenFns = [];
this.catchFns = [];
this.status = STATUS.PENDING;
this.resolve = (value) => {
this.resolvedValue = value;
this.status = STATUS.RESOLVED;
this.thenFns.forEach((fn) => fn(value));
}
this.reject = (value) => {
this.rejectedValue = value;
this.status = STATUS.REJECTED;
this.catchFns.forEach((fn) => fn(value));
}
fn(this.resolve, this.reject);
}
then(_then) {
if (this.status === STATUS.PENDING) {
return new Pact((resolve, reject) => {
this.thenFns.push((val) => {
if (val instanceof Pact) {
val.then((val) => resolve(_then(val)));
}
else {
resolve(_then(val));
}
});
});
}
else if (this.status === STATUS.RESOLVED) {
_then(this.resolvedValue);
}
}
catch(_catch) {
if (this.status === STATUS.PENDING) {
this.catchFns.push(_catch);
}
else if (this.status === STATUS.REJECTED) {
_catch(this.rejectedValue);
}
}
}
module.exports = Pact;