-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest.js
50 lines (43 loc) · 1.11 KB
/
test.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
function Promise(excutor) {
let self = this;
self.status = "padding";
self.value = undefined;
self.reason = undefined;
self.onResolvedCallback = [];
self.onRejectedCallback = [];
// 修改状态,保存值
function resolve(value) {
if (self.status === "padding") {
self.status = "resolved";
self.value = value
self.onResolvedCallback.forEach(item => item(self.value));
}
}
function reject(reason) {
if (self.status === "padding") {
self.status = "rejected";
self.reason = reason;
self.onRejectedCallback.forEach(item => item(self.reason));
}
}
try {
excutor(resolve, reject)
} catch (error) { //有错误会走向失败
reject(error)
}
}
Promise.prototype.then = function (onFulfilled, onRejected) {
let self = this;
// 执行方法,传入值
if (self.status === "resolved") {
onFulfilled(self.value);
}
if (self.status === "rejected") {
onRejected(self.reason);
}
// 处理异步情况
if (self.status === "padding") {
self.onResolvedCallback.push(onRejected);
self.onRejectedCallback.push(onFulfilled);
}
}