class MyPromise {
constructor(fn) {
this.state = 'pending'
this.resolveVal = null
this.rejectVal = null
this.resolveCbArr = []
this.rejectCbArr = []
fn(this.resolve.bind(this), this.reject.bind(this))
}
resolve(val) {
if (this.state === 'pending') {
this.state = 'resolve'
this.resolveVal = val
this.resolveCbArr.map(cb => cb(this.resolveVal))
}
}
reject(val) {
if (this.state === 'pending') {
this.state = 'reject'
this.rejectVal = val
this.rejectCbArr.map(cb => cb(this.rejectVal))
}
}
then(resolveCb, rejectCb) {
if(this.state === 'pending') {
this.resolveCbArr.push(resolveCb)
this.rejectCbArr.push(rejectCb)
}
if (this.state === 'resolve') {
resolveCb(this.resolveVal)
}
if (this.state === 'reject') {
rejectCb(this.rejectVal)
}
}
}
const p1 = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve(111)
}, 2000)
}).then(res => {
console.log(res)
}, () => {
})
console