class MyPromise {
static PENDING = 'pending'
static FULFILLED = 'fulfilled'
static REJECTED = 'rejected'
state = MyPromise.PENDING
result = null
constructor(fun) {
this.status = MyPromise.PENDING
this.result = null
try {
fun(this.resolve, this.reject)
} catch (error) {
this.reject(error)
}
}
resolve = (result) => {
setTimeout(() => {
if (this.status === MyPromise.PENDING) {
this.status = MyPromise.FULFILLED
this.result = result
this.resolveCallBacks.forEach(callback => {
callback(result)
})
}
})
}
reject = (result) => {
setTimeout(() => {
if (this.status === MyPromise.PENDING) {
this.status = MyPromise.REJECTED
this.result = result
this.rejectCallBacks.forEach(callback => {
callback(result)
})
}
})
}
then = (onFULFILLED, onREJECTED) => {
return new MyPromise((resolve, reject) => {
onFULFILLED = typeof onFULFILLED === 'function' ? onFULFILLED : () => { }
onREJECTED = typeof onREJECTED === 'function' ? onREJECTED : () => { }
this.resolveCallBacks = []
this.rejectCallBacks = []
if (this.status === MyPromise.PENDING) {
this.resolveCallBacks.push(onFULFILLED)
this.rejectCallBacks.push(onREJECTED)
}
if (this.status === MyPromise.FULFILLED) {
setTimeout(() => {
onFULFILLED(this.result)
})
}
if (this.status === MyPromise.REJECTED) {
setTimeout(() => {
onREJECTED(this.result)
})
}
})
}
}
console.log(1)
let m = new MyPromise((resolve, reject) => {
console.log(2)
setTimeout(() => {
resolve('1s')
reject('2s')
console.log(4)
})
})
m.then(
(res) => { console.log(res) },
(res) => { console.log(res.message) }
).then()
console.log(3)