class myPromise {
constructor(executor) {
//1.参数的校验
if (typeof executor !== 'function') {
throw new TypeError('is not a function')
}
this.initValue()
this.initBind()
try {
executor(this.resolve, this.reject)
} catch (error) {
this.reject(error)
}
}
initValue() {
// 2.初始化数据
this.value = null;
this.state = 'pending';
this.reason = null;
this.onFulfilledCallBacks = []
this.onRejectedCallBacks = []
}
initBind(){
this.resolve=this.resolve.bind(this)
this.reject=this.reject.bind(this)
}
resolve(value) {
// 1.更改promise的状态,执行成功的回调函数
if (this.state !== 'pending') return
this.state = 'fulfilled'
this.value = value
this.onFulfilledCallBacks.forEach(fn=>fn(this.value))
}
reject(reason){
if (this.state !== 'pending') return
this.state = 'rejected'
this.reason = reason
this.onRejectedCallBacks.forEach(fn=>fn(this.reason))
}
then(onFulfilled,onRejected){
if(typeof onFulfilled !=='function'){
onFulfilled = function(value){
return value
}
}
if(typeof onRejected !== 'function'){
onRejected = function(value){
return value
}
}
if(this.state === 'fulfilled'){
setTimeout(()=>{
onFulfilled(this.value)
})
}
if(this.state === 'rejected'){
setTimeout(()=>{
onRejected(this.reason)
})
}
if(this.state === 'pending'){
this.onFulfilledCallBacks.push(value=>{
setTimeout(()=>{
onFulfilled(value)
})
})
this.onRejectedCallBacks.push(reason=>{
setTimeout(()=>{
onRejected(reason)
})
})
}
}
}
module.exports = myPromise
promise
最新推荐文章于 2025-04-23 17:48:22 发布