-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.js
50 lines (50 loc) · 1.39 KB
/
promise.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
export default class MyPromise {
static PENDING = 'pending';
static SUCCESS = 'fulfilled';
static REJECTED = 'rejected';
constructor(executor) {
this.result = null;
this.status = MyPromise.PENDING;
this.resolveCallback = [];
this.rejectCallback = [];
try {
executor(this.resolve.bind(this), this.reject.bind(this));
} catch (err) {
this.reject(err);
}
}
resolve(res) {
if (this.status === MyPromise.PENDING) {
setTimeout(() => {
this.status = MyPromise.SUCCESS;
this.result = res;
this.resolveCallback.forEach((cb) => cb(res));
});
}
}
reject(reason) {
if (this.status === MyPromise.PENDING) {
setTimeout(() => {
this.status = MyPromise.REJECTED;
this.result = reason;
this.rejectCallback.forEach((cb) => cb(reason));
});
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : () => {};
onRejected = typeof onRejected === 'function' ? onRejected : () => {};
setTimeout(() => {
if (this.status === MyPromise.PENDING) {
this.resolveCallback.push(onFulfilled);
this.rejectCallback.push(onRejected);
}
if (this.status === MyPromise.SUCCESS) {
onFulfilled(this.result);
}
if (this.status === MyPromise.REJECTED) {
onRejected(this.result);
}
});
}
}