class Promise {
PromiseStatus = 'pending'
PromiseResult = null
callback = []
constructor(executor) {
let resolve = (data) => {
if(this.PromiseStatus != 'pending') return
this.PromiseStatus = 'fulfilled'
this.PromiseResult = data
this.callback.forEach(item => {
console.log(this.PromiseStatus)
console.log(1)
item.onResolved()
})
}
let reject = (data) => {
if(this.PromiseStatus != 'pending') return
this.PromiseStatus = 'rejected'
this.PromiseResult = data
this.callback.forEach(item => {
item.onRejected()
})
}
try {
executor(resolve, reject)
} catch (error) {
reject(error)
}
}
then(onResolved, onRejected) {
let call = (type) => {
try {
let result = type(this.PromiseResult)
if(result instanceof Promise) {
result.then(res => {
resolve(res)
}, err => {
reject(err)
})
}
} catch (error) {
reject(err)
}
}
return new Promise((resolve, reject) => {
if(this.PromiseStatus === 'fulfilled') {
call(onResolved)
}
if(this.PromiseStatus === 'rejected') {
call(onRejected)
}
if(this.PromiseStatus === 'pending') {
this.callback.push({
onResolved:function() {
call(onResolved)
},
onRejected:function() {
call(onRejected)
}
}
)
}
})
}
static resolve(data) {
return new Promise((resolve, reject) => {
if(data instanceof Promise) {
data.then((res) => {
resolve(res)
}, (err) => {
reject(err)
})
} else {
resolve(data)
}
})
}
}
Promise实现原理,Class版本
最新推荐文章于 2024-07-30 23:06:43 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)