class Promise{
state = 'pending'
callbacks = []
value = undefined
constructor(fn){
fn(this._resolve.bind(this), this._reject.bind(this)
}
_resolve(value){
this.state = 'fullfiled'
this.value = value
this.callbacks.foreach(callback => this._handle(callback))
}
_reject(error){
this.state = 'rejected'
this.value = error
this.callbacks.foreach(callback => this._handle(callback))
}
_handle(callback){
if( this.state === 'pending') {
this.callbacks.push(callback)
return
}
let cb = this.state === 'fullfilled' ? callback.onFulfilled : callback.onRejected
if (!cb) {
// 没定义 onFulfilled 或者 onRejected
cb = this.state === 'fullfilled' ? callback.resolve : callback.reject
cb(this.value)
return
}
const ret = cb()
cb(ret)
}
then(onFulfilled = null, onRejected = null){
// 每次 then 都会创建新的 Promise 实例
return new Promise((resolve, reject) => {
this._handle(onFulfilled, onRejected, resolve, reject)
}
}
catch(onError){
// onFulfill为null,仅在onReject里面被调用
return this.then(null, onError)
}
}