-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
3.2.promise.js
65 lines (59 loc) · 1.51 KB
/
3.2.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* 简易版1.0.1
* @param {Function} executor
*/
// 1.promise需要有三个状态
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class Promise {
constructor(executor) {
let self = this
self.status = PENDING
self.value = undefined
self.reason = undefined
self.onResolvedCallbacks = []
self.onRejectedCallbacks = []
const resolve = (value) => {
if(self.status === PENDING){
self.value = value
self.status = FULFILLED
self.onResolvedCallbacks.forEach((fn) => {
fn()
})
}
}
const reject = (reason) => {
if(self.status === PENDING){
self.reason = reason
self.status = REJECTED
self.onRejectedCallbacks.forEach((fn) => {
fn()
})
}
}
try{
executor(resolve, reject) // 如果执行这个executor执行时候抛出异常 应该走下一个then的失败
}catch(e){
reject(e)// 出错了 reason就是错误
}
}
then (onFulfilled, onRejected) {
if (this.status === FULFILLED){
onFulfilled(this.value)
}
if (this.status === REJECTED){
onRejected(this.reason)
}
if( this.status === PENDING){
// 默认当前 new Promise executor中是有异步的
this.onResolvedCallbacks.push(() => {
onFulfilled(this.value)
});
this.onRejectedCallbacks.push(() => {
onRejected(this.reason)
})
}
}
}
module.exports = Promise