class MyPromise {
static PENDING = 'pending'
static FULFILLED = 'fulfilled'
static REJECTED = 'rejected'
constructor(executor) {
this.status = MyPromise.PENDING
this.result = undefined
this.resolveCallBacks = []
this.rejectCallBacks = []
try {
executor(this.resolve, this.reject)
} catch (reason) {
this.reject(reason)
}
}
resolve = value => {
if (this.status === MyPromise.PENDING) {
this.status = MyPromise.FULFILLED
this.result = value
this.resolveCallBacks.forEach(callback => callback(value))
}
}
reject = reason => {
if (this.status === MyPromise.PENDING) {
this.status = MyPromise.REJECTED
this.result = reason
this.rejectCallBacks.forEach(callback => callback(reason))
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled ==='function' ? onFulfilled :()=>{}
onRejected = typeof onRejected ==='function' ? onRejected :()=>{}
if (this.status === MyPromise.FULFILLED) {
setTimeout(() => {
onFulfilled(this.result)
})
}
if (this.status === MyPromise.REJECTED) {
setTimeout(() => {
onRejected(this.result)
})
}
if (this.status === MyPromise.PENDING) {
this.resolveCallBacks.push(onFulfilled)
this.resolveCallBacks.push(onRejected)
}
}
}
let p = new MyPromise((resolve, reject) => {
throw new Error('fail')
})
p.then(
res => { console.log(res) },
err=>{ console.log(err.message)}
)