class MyPromise {
static PENDDING = '等待'
static RESLOVE = '完成'
static REJECT = '拒绝'
result = null
status = null
resloveCallback = []
rejectCallback = []
constructor(func) {
this.status = MyPromise.PENDDING
func(this.reslove.bind(this), this.reject.bind(this))
}
reslove(result) {
setTimeout(() => {
if (this.status === MyPromise.PENDDING) {
this.status = MyPromise.RESLOVE
this.result = result
this.resloveCallback.forEach(callback => {
callback()
})
}
})
}
reject(result) {
setTimeout(() => {
if (this.status === MyPromise.PENDDING) {
this.status = MyPromise.REJECT
this.result = result
this.rejectCallback.forEach(callback => {
callback()
})
}
})
}
then(onReslove, onReject) {
onReslove = typeof onReslove == 'function' ? onReslove : () => { }
onReject = typeof onReject == 'function' ? onReject : () => { }
if (this.status === MyPromise.PENDDING) { //这里经常cb保存操作
this.resloveCallback.push(onReslove)
this.rejectCallback.push(onReject)
}
if (this.status === MyPromise.RESLOVE) {
setTimeout(() => {
onReslove(this.result)
})
}
if (this.status === MyPromise.REJECT) {
setTimeout(() => {
onReject(this.result)
})
}
}
catch(onReject) {
onReject = typeof onReject == 'string' ? onReject : () => { }
if (this.status === MyPromise.REJECT) {
setTimeout(() => {
onReject(this.result)
})
}
}
}
new MyPromise((reslove, reject) => {
reslove('这是结果')
}).then((reslut) => {
console.log('reslut', reslut)
})
new MyPromise((reslove, reject) => {
setTimeout(() => {
reslove('这是结果')
})
}).then((reslut) => {
console.log('reslut', reslut)
})
坑:
- promise内的reslove和reject函数 需要绑定this的指向
- promise内的状态三种,一定是到状态后才会切换执行回调,没到直接推入回调数组中等待到达状态后执行。
- promise的做到异步是通过setTimeout来实现的