Promise实现
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MPromise {
FULFILLED_CALLBACK_LIST = []
REJECTED_CALLBACK_LIST = []
_status = PENDING
constructor(fn) {
this.status = PENDING
this.value = null
this.reason = null
try {
fn(this.resolve.bind(this), this.reject.bind(this))
} catch (e) {
this.reject(e)
}
}
get status() {
return this._status
}
set status(newStatus) {
this._status = newStatus
switch (newStatus) {
case FULFILLED: {
this.FULFILLED_CALLBACK_LIST.forEach((callback) => {
callback(this.value)
})
break
}
case REJECTED: {
this.REJECTED_CALLBACK_LIST.forEach((callback) => {
callback(this.reason)
})
break
}
}
}
resolve(value) {
if (this.status === PENDING) {
this.value = value
this.status = FULFILLED