-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise.html
85 lines (68 loc) · 2.09 KB
/
promise.html
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
function MyPromise(callback) {
if (!callback) return
this.state = 'pending'
this.data = null
this.resolveCallback = []
this.rejectCallback = []
this.resolve = () => {
console.log(this);
if (this.state === 'pending') {
this.state = 'resolved'
this.resolveCallback.forEach(item => {
item()
});
}
}
this.reject = () => {
if (this.state === 'pending') {
this.state = 'rejected'
this.rejectCallback.forEach(item => {
item()
});
}
}
callback(this.resolve, this.reject)
}
MyPromise.prototype.then = function (thenCallback) {
return new MyPromise()
}
function Promise(fn) {
this.cbs = [];
const resolve = (value) => {
setTimeout(() => {
this.data = value;
this.cbs.forEach((cb) => cb(value));
});
}
fn(resolve);
}
Promise.prototype.then = function (onResolved) {
return new Promise((resolve) => {
this.cbs.push(() => {
const res = onResolved(this.data);
if (res instanceof Promise) {
res.then(resolve);
} else {
resolve(res);
}
});
});
};
// new MyPromise((resolve, reject) => {
// console.log(999);
// resolve(999)
// }).then(() => {
// })
</script>
</body>
</html>