-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromise_implement.html
More file actions
74 lines (72 loc) · 2.63 KB
/
promise_implement.html
File metadata and controls
74 lines (72 loc) · 2.63 KB
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
<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>
<script>
class Promise {
constructor(excutor) {
// 需要确保 excutor 为函数
if (typeof excutor !== 'function') {
throw new Error('excutor must be a function')
}
// 当前promise的状态
this.state = 'pending' //fulfilled、rejected
// 当状态为 fulfilled 时的 value
this.value = undefined
// 当状态为 rejected 时的 reason
this.reason = undefined
// 缓存 Resolved 状态下的回调函数
this.onResolvedCallbacks = []
// 缓存 Rejected 状态下的回调函数
this.onRejectedCallbacks = []
let resolve = (value) => {
if (value instanceof Promise) {
return value.then(resolve, reject);
}
// 实践中要确保 onFulfilled 和 onRejected 方法异步执行,且应该在 then 方法被调用的那一轮事件循环之后的新执行栈中执行。
setTimeout(() => {
// 调用resolve 回调对应onFulfilled函数
if (this.state === 'pending') {
this.state = 'fulfilled'
this.value = value
this.onResolvedCallbacks.forEach(fn => fn())
}
});
}
let reject = (reason) => {
setTimeout(() => {
if (this.state === 'pending') {
this.state = 'fulfilled、rejected'
this.reason = reason
this.onRejectedCallbacks.forEach(fn => fn())
}
})
}
try {
excutor(resolve, reject)
} catch (error) {
reject(error)
}
}
then(onFulfilled, onRejected) {
if (this.state === 'fulfilled') {
onFulfilled(this.value)
}
if (this.state === 'rejected') {
onRejected(this.reason)
}
if (this.state === 'pending') {
this.onResolvedCallbacks.push(() => {
onFulfilled(this.value)
})
this.onRejectedCallbacks.push(() => {
onRejected(this.reason)
})
}
}
}
</script>
</html>