-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest.js
94 lines (81 loc) · 2.12 KB
/
test.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const PENDING = 'PENDING',
FULFILLED = 'FULFILLED',
REJECTED = 'REJECTED'
class BasePromise {
constructor(executor) {
this.status = PENDING
this.value = undefined
this.reason = undefined
this.resolve = this.resolve.bind(this)
this.reject = this.reject.bind(this)
this.onResolvedCallbacks = []
this.onRejectedCallbacks = []
try {
executor(this.resolve, this.reject)
} catch (error) {
this.reject(error)
}
}
resolve(value) {
if (this.status === PENDING) {
this.value = value
this.status = FULFILLED
this.onResolvedCallbacks.forEach((fn) => {
fn(this.value)
})
}
}
reject(reason) {
if (this.status === PENDING) {
this.reason = reason
this.status = REJECTED
this.onRejectedCallbacks.forEach((fn) => {
fn(this.reason)
})
}
}
// 这里只能处理包含一个then方法,并接收两个参数onFulfilled, onRejected
then(onFulfilled, onRejected) {
// 成功提交
if (this.status === FULFILLED) {
onFulfilled(this.value)
} else if (this.status === REJECTED) {
// 失败提交
onRejected(this.reason)
} else if (this.status === PENDING) {
// 如果promise的状态是PENDING,需要将onFulfilled和onRejected函数存放起来,等待状态确定后,再依次执行对应的函数
this.onResolvedCallbacks.push(() => {
this.value = onFulfilled(this.value)
})
this.onRejectedCallbacks.push(() => {
this.reason = onRejected(this.reason)
})
}
}
catch() {}
}
// let data = new BasePromise((res,rej) => {
// console.log(112)
// res(333)
// })
const promise = new BasePromise((resolve, reject) => {
setTimeout(() => {
console.log('success')
resolve('success')
}, 2000);
})
promise.then(() => {
return new BasePromise((res, rej) => {
setTimeout(() => {
console.log('success2')
resolve('success2')
}, 2000);
})
}).then(() => {
console.log('end')
})
// promise.then(value => {
// console.log('resolve', value)
// }, reason => {
// console.log('reject', reason)
// })