const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'
function MyPromise(fn) {
const that = this //方便后面利用上下文,先把this赋值给that
this.state = PENDING // 初始状态为pending
this.value = null
this.resolvedCallbacks = [] // 这两个变量用于保存then中的回调,因为执行完Promise时状态可能还是pending
this.rejectedCallbacks = [] // 此时需要吧then中的回调保存起来方便状态改变时调用
function resolve(value) {
if(that.state === PENDING) {
that.state = RESOLVED // resolve函数执行时,若状态为pending,则把状态转换为resolved
that.value = value // 把值赋给this.value
that.resolvedCallbacks.map(cb => cb(value)) // 遍历数组,执行之前保存的then的回调函数
}
}
function reject(value) {
if(that.state === PENDING) { // 同上
that.state = REJECTED
that.value = value
that.rejectedCallbacks.map(cb => cb(value))
}
}
try{
手动实现简易的Promise
最新推荐文章于 2024-04-26 09:23:58 发布