Promise函数总体架构
结构图
上代码
const PENDING = 'padding'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
constructor(executor) {
executor(this.resolve, this.reject)
}
value = null
reason = null
status = PENDING
successArr = []
errorArr = []
i = 0
resolve = value => {
if (this.status !== PENDING) return;
this.value = value
this.status = FULFILLED
console.log(this.i);
while (this.successArr.length) this.successArr.shift()(value)
}
reject = reason => {
if (this.status !== PENDING) return;
this.reason = reason
this.status = REJECTED
while (this.errorArr.length) this.errorArr.shift()(value)
}
then(success, error) {
if (this.status === FULFILLED) {
success(this.value)
} else if (this.status === REJECTED) {
error(this.reason)
} else {
this.successArr.push(success)
this.errorArr.push(error)
}
}
}
let promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('雷好')
}, 2000)
})
promise.then((value) => {
console.log(value);
},
(reason) => {
console.log(reason);
}
)