手写Promise
# 一、promise特性
# 1.主流程
# 2.promise三种状态
pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation was completed successfully.
rejected: meaning that the operation failed.
# 3.promise.then支持链式调用
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo')
}, 300)
})
myPromise
.then(handleResolvedA, handleRejectedA)
.then(handleResolvedB, handleRejectedB)
.then(handleResolvedC, handleRejectedC)
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 二、手写promise
# 1.框架
实现promise主要需要实现以下几个方法
function MyPromise() {}
MyPromise.prototype.then = function() {}
MyPromise.prototype.catch = function() {}
MyPromise.prototype.all = function() {}
MyPromise.prototype.race = function() {}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 2.实现 MyPromise
function MyPromise(executor) {
this.status = 'pending' // pending fulfilled rejected
this.fulfilledCallback = []
this.rejectedCallback = []
this.success = undefined
this.failed = undefined
let that = this
function resolve(params) {
if (that.status === 'pending') {
that.status = 'fulfilled'
that.success = params
that.fulfilledCallback.forEach((func) => {
func(params)
})
}
}
function reject(params) {
if (that.status === 'pending') {
that.status = 'rejected'
that.failed = params
that.rejectedCallback.forEach((func) => {
func(params)
})
}
}
executor(resolve, reject)
}
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
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
# 3.实现.then和链式调用
MyPromise.prototype.then = function(
fulfilledFunc,
rejectedFunc = function() {}
) {
return new MyPromise((resolve, reject) => {
if (this.status === 'fulfilled') {
const res = fulfilledFunc(this.success)
resolve(res)
}
if (this.status === 'rejected ') {
const res = rejectedFunc(this.failed)
resolve(res)
}
if (this.status === 'pending') {
this.fulfilledCallback.push(() => {
const res = fulfilledFunc(this.success)
resolve(res)
})
this.rejectedCallback.push(() => {
const res = rejectedFunc(this.failed)
resolve(res)
})
}
})
}
let p2 = new MyPromise((resolve, reject) => {
setTimeout(() => {
// reject(new Error('error'))
resolve('resolve success')
}, 2000)
})
p2.then((res) => {
console.log('step1 then', res)
return res
}).then((res) => {
console.log('step2 then', res)
})
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
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
上次更新: 2023/04/05, 09:41:10