function myPromise(excutor){ // 用self来接收this let self = this // 定义初始状态 self.status = 'pending' // 定义成功的信息 self.success = null // 定义失败的信息 self.fail = null
// 定义缓存
self.onFulfilledCallbacks = []
self.onRejectedCallbacks = []
// 成功的回调
function reslove(value){
if(self.status == 'pending'){
self.status = 'fulfilled'
self.success = value
self.onFulfilledCallbacks.forEach(item => item(value))
}
}
// 失败的回调
function reject(error){
if(self.status == 'pending'){
self.status = 'rejected'
self.fail = error
self.onRejectedCallbacks.forEach(item => item(error))
}
}
try {
// 立即执行
excutor(reslove,reject)
} catch (error) {
reject(error)
}
}
// 在原型上定义then方法
myPromise.prototype.then = function(onFulfilled,onRejected){
onFulfilled =typeof onFulfilled === 'function' ? onFulfilled : function(onFulfilled){reslove(onFulfilled)}
onRejected = typeof onRejected === 'function' ? onRejected : function(onRejected){throw 'error'}
let self = this
self.onFulfilledCallbacks.push(onFulfilled)
self.onRejectedCallbacks.push(onRejected)
}