# promise 实现
promise有三种状态,Pending、Fulfilled、Rejected,分别是进行中、成功、拒绝三种,初始化是Pending状态
const PENDING = 'Pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
constructor(fn) {
this._state = PENDING
this._value = undefined
this._fulfilledCbs = []
this._rejectedCbs = []
try {
fn(this.resolve, this.reject)
} catch(err) {
this.reject(err)
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
promise是根据then方法来收集回调的,即promise执行resolve或者reject之后的回调,并且返回一个新的promise
class MyPromise {
then(onFulfilled, onRejected) {
const newPromise = new MyPromise((nextResolve, nextReject) => {
// 如果 then 里面不传参数,则 onFulfilled、onRejected 也应该有默认值
// MyPromise
// .resolve(1)
// .then()
// .then(val => {
// // 这里应该还可以拿到 val 值
// })
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (value => value)
onRejected = typeof onRejected === 'function' ? onRejected : (error => { throw error })
const fulfilledCb = () => {
try {
let res = onFulfilled(this._value)
if (res instanceof MyPromise) {
res.then.call(res, nextResolve)
return
}
nextResolve(res)
} catch(e) {
nextReject(this._value)
}
}
const rejectedCb = () => {
try {
let res = onRejected(this._value)
if (res instanceof MyPromise) {
res.then.call(res, nextResolve)
return
}
nextResolve(res)
} catch(e) {
nextReject(this._value)
}
}
// 三种状态处理
if (this._state === PENDING) {
this._fulfilledCbs.push(fulfilledCb)
this._rejectedCbs.push(rejectedCb)
} else if (this._state === FULFILLED) {
fulfilledCb()
} else {
rejectedCb()
}
})
// 返回新的 Promise
return newPromise
}
}
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
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
- 当执行
promise的resolve方法时,会调用then方法收集的回调
class MyPromise {
resolve = (value) => {
if (this._state === PENDING) {
this._state = FULFILLED
this._value = value
// 执行 then 收集的 fulfilled 回调函数
while(this._fulfilledCbs.length) {
(this._fulfilledCbs.shift())()
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12