class MyPromise {
constructor(executor) {
this.status = 'pending'
this.value = null
this.reason = null
this.onFulfilledArray = []
this.onRejectedArray = []
const resolve = (value) => {
setTimeout(() => {
this.value = value
this.status = 'fulfilled'
this.onFulfilledArray.forEach(func => {
func(value)
})
})
}
const reject = (reason) => {
setTimeout(() => {
this.reason = reason
this.status = 'rejected'
this.onRejectedArray.forEach(func => {
func(reason)
})
})
}
executor(resolve, reject)
}
then(onfulfilled, onrejected) {
onfulfilled = typeof onfulfilled === 'function' ? onfulfilled : data => data
onrejected = typeof onrejected === 'function' ? onrejected : error => error
if (this.status = 'fulfilled') {
this.value = onfulfilled(this.value)
}
if (this.status = 'rejected') {
onrejected(this.reason)
}
if (this.status = 'pending') {
this.onFulfilledArray.push(onfulfilled)
this.onRejectedArray.push(onrejected)
}
}
}
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('data')
}, 1000)
reject('error')
})
promise
.then((data) => {
console.log(data)
}, (error) => {
})