我们需要明白Promise的基本原理:
Promise 是一个类,在执行这个类的时候会传入一个执行器,这个执行器会立即执行
Promise 会有三种状态
Pending 等待
Fulfilled 完成
Rejected 失败
状态只能由 `Pending --> Fulfilled` 或者 `Pending --> Rejected`,且一但发生改变便不可二次修改;
Promise 中使用 `resolve` 和 `reject` 两个函数来更改状态;
`then` 方法内部做但事情就是状态判断:
如果状态是成功,调用成功回调函数
如果状态是失败,调用失败回调函数
如果是`pending`状态,则会将`then`中的函数添加到执行回调中
代码实现
测试的html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./myPromise.js"></script>
</head>
<body>
<script>
let myPromise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('success')
}, 2000)
})
myPromise.then(
(value) => {
console.log('resolve', value)
},
(reason) => {
console.log('reject', reason)
}
)
</script>
</body>
</html>
测试的JS
const PENDING = 'PENDING'
const FULFILLED = 'fulfilled'
const REGEDTED = 'rejected'
class MyPromise {
constructor(executor) {
executor(this.resolve, this.reject)
}
status = PENDING
value = null
reason = null
onFulfilledCallback = null
onRejectedCallback = null
resolve = (value) => {
if (this.status === PENDING) {
this.status = FULFILLED
this.value = value
this.onFulfilledCallback && this.onFulfilledCallback(value)
}
}
reject = (reason) => {
if (this.status === PENDING) {
this.status = REGEDTED
this.reason = reason
this.onRejectedCallback && this.onRejectedCallback(reason)
}
}
then(onFulfilled, onRegected) {
if (this.status === FULFILLED) {
onFulfilled(this.value)
} else if (this.status === REGEDTED) {
onRegected(this.reason)
} else if (this.status === PENDING) {
this.onFulfilledCallback = onFulfilled
this.onRejectedCallback = onRegected
}
}
}
参考文章:juejin.cn/post/694531…