-
Notifications
You must be signed in to change notification settings - Fork 0
/
myPromise.js
57 lines (52 loc) · 1.27 KB
/
myPromise.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
52
53
54
55
56
57
const PENDING = 'pending';
const RESOLVED = 'resolved';
const REJECTED = 'rejected';
function MyPromise(fn) {
const self = this;
self.state = PENDING;
self.value = null;
self.resolvedCallbacks = [];
self.rejectedCallbacks = [];
function resolve(value) {
if (value instanceof MyPromise) {
return value.then(resolve, reject);
}
if (self.state === PENDING) {
self.state = RESOLVED;
self.value = value;
self.resolveCallbacks.map(cb => cb(value));
}
}
function rejected(value) {
if (self.state === PENDING) {
self.state = REJECTED;
self.state = value;
self.rejectedCallbacks.map(cb => cb(value));
}
}
try {
fn(resolve, rejected);
} catch (e) {
rejected(e);
}
}
MyPromise.prototype.then = function(onFullfilled, onRejected) {
const self = this;
onFullfilled = typeof onFullfilled === 'function' ? onFullfilled : v => v;
onRejected =
typeof onRejected === 'function'
? onRejected
: e => {
throw e;
};
if (self.state === PENDING) {
self.resolvedCallbacks.push(onFullfilled);
self.rejectedCallbacks.push(onRejected);
}
if (self.state === RESOLVED) {
onFullfilled(self.value);
}
if (self.state === REJECTED) {
onRejected(self.value);
}
};