简洁版Promise
const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'
function MyPromise(fn){
let that = this
this.state = PENDING
this.value = null
this.resolvedCallbacks = []
this.rejectedCallbacks = []
function resolve(value){
if(that.state === PENDING){
that.state = RESOLVED
that.value = value
that.resolvedCallbacks.map(item => item(value))
}
}
function reject(value){
if(that.state === PENDING){
that.state = REJECTED
that.value = value
that.rejectedCallbacks.map(item => item(value))
}
}
try{
fn(resolve, reject)
}
catch(e){
reject(e)
}
}
MyPromise.prototype.then = function(onFulfilled,onRejected){
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v=>v
onRejected = typeof onRejected === 'function' ? onRejected : e=>throw e
if(this.state === PENDING){
this.resolvedCallbacks.push(onFulfilled)
this.rejectedCallbacks.push(onRejected)
}
if(this.state === RESOLVED) {
onFulfilled(this.value)
}
if(this.state === REJECTED) {
onRejected(this.value)
}
}