class Commitment {
static PENDING = 'pending'
static RESOLVED = 'resolved'
static REJECTED = 'rejected'
constructor(func){
this.state = Commitment.PENDING
this.value = null
this.resolveCallbacks = []
this.rejectCallbacks = []
try {
func(this.resolve.bind(this),this.reject.bind(this) )
} catch (error) {
this.reject(error)
}
}
resolve(value){
setTimeout(()=>{
if(this.state==='resolved'){
this.state=Commitment.RESOLVED
this.value = value
this.resolveCallbacks.forEach(cb=>cb(value))
}
})
}
reject(value){
setTimeout(()=>{
if(this.state==='rejected'){
this.state=Commitment.REJECTED
this.value = value
this.rejectCallbacks.forEach(cb=>cb(value))
}
})
}
then(onFulfilled,onRejected){
if(this.state===Commitment.PENDING){
onFulfilled = typeof onFulfilled ==='function'?onFulfilled : ()=>{}
onRejected = typeof onRejected === 'function'?onRejected : ()=>{}
this.rejectCallbacks.push(onRejected)
this.resolveCallbacks.push(onFulfilled)
}
if(this.state===Commitment.RESOLVED){
setTimeout(()=>{
onFulfilled(this.value)
})
}
if(this.state===Commitment.REJECTED){
setTimeout(()=>{
onRejected(this.value)
})
}
}
}