-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathmy-promise.js
46 lines (45 loc) · 1.2 KB
/
my-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
export function MyPromise(executor) {
this.state = "pending";
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
executor(
data => {
this.state = "resolved";
this.value = data;
this.onFulfilledCallbacks.forEach(callback => {
callback(data);
});
},
err => {
this.state = "rejected";
this.value = err;
this.onRejectedCallbacks.forEach(callback => {
callback(err);
});
}
);
}
MyPromise.prototype.then = function(onSuccess, onFail) {
let callback = null;
if (this.state === "resolved") {
let newValue = onSuccess(this.value);
callback(newValue);
}
if (this.state === "pending") {
this.onFulfilledCallbacks.push(res => {
let newValue = onSuccess(res);
callback(newValue);
});
this.onRejectedCallbacks.push(error => {
onFail(error);
});
}
if (this.state === "rejected") {
onFail(this.value);
}
return new Promise((resolve, reject) => {
callback = data => {
resolve(data);
};
});
};