const PENDING = "pending"
const FULLFILLED = "fullfilled"
const REJECTED = "rejected"
class NumoPromise {
constructor(exector) {
if (typeof exector !== 'function') throw Error('exector params must be a function')
this.status = PENDING
this.value = undefined
this.reason = undefined
const resolve = (value) => {
if (this.status === 'pending') {
queueMicrotask(() => {
if (this.status !== PENDING) return
this.status = FULLFILLED
this.value = value
console.log(value)
})
}
}
const reject = (reason) => {
if (this.status === 'pending') {
queueMicrotask(() => {
if (this.status !== PENDING) return
this.status = REJECTED
this.reason = reason
console.log(reason)
})
}
}
exector(resolve, reject)
}
then(successFn, failFn) {
this.successFns = successFn
this.failFns = failFn
if (this.status === 'fullfilled') {
successFn(this.value)
}
if (this.status === 'rejected') {
failFn(this.reason)
}
}
}
/**
* 解决1: 解决了NumoPromise中exector异步执行
* 解决2: 加上了一个.then方法
*/
const np = new NumoPromise((resolve, reject) => {
setTimeout(() => {
reject('error')
}, 3000)
})
np.then((value) => console.log(value), (reason) => console.log(reason))
console.log('先执行')