-
Notifications
You must be signed in to change notification settings - Fork 0
/
Promise.js
37 lines (34 loc) · 871 Bytes
/
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
class MyPromise {
static PENDING = "pending";
static FUllFILLED = "fullfilled";
static REJECT = "reject";
constructor(fn) {
this.result = null;
this.status = MyPromise.PENDING;
fn(this.resolve.bind(this), this.reject.bind(this));
}
resolve(result) {
if (this.status === MyPromise.PENDING) {
this.result = result;
this.status = MyPromise.FUllFILLED;
}
}
reject(result) {
if (this.status === MyPromise.PENDING) {
this.result = result;
this.status = MyPromise.REJECT;
}
}
then(onFullFilled, onReject) {
if (this.status === MyPromise.FUllFILLED) {
onFullFilled(this.result);
}
if (this.status === MyPromise.REJECT) {
onReject(this.result);
}
}
}
const promise = new MyPromise((resolve, reject) => {
resolve(123);
});
promise.then((result) => console.log(result));