-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise.js
63 lines (58 loc) · 1.3 KB
/
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
const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'
class MyPromise {
constructor(fn) {
this.state = PENDING
//终值
this.value = null
//拒因
this.reason = null
//成功回调队列
this.onResolvedCbs = []
//拒绝回调队列
this.onRejectedCbs = []
const resolve = value => {
setTimeout(() => {
if(this.state === PENDING) {
this.state = RESOLVED
this.value = value
this.onResolvedCbs.map(cb => {
this.value = cb(this.value)
})
}
})
}
const reject = reson => {
setTimeout(() => {
if(this.state === PENDING) {
this.state = REJECTED
this.reason = reson
this.onRejectedCbs.map(cb => {
this.reason = cb(this.reason)
})
}
})
}
try {
fn(resolve, reject)
} catch(e) {
reject(e)
}
}
then(onResolved, onRejected) {
typeof onResolved === 'function' && this.onResolvedCbs.push(onResolved)
typeof onRejected === 'function' && this.onRejectedCbs.push(onRejected)
return this
}
}
new MyPromise((resolve,reject) => {
setTimeout(() => {
resolve(3)
},1000)
}).then(res => {
console.log(res)
return res + 1
}).then(res => {
console.log(res)
})