const PROMISE_STATUS_PEDDING = 'pedding'
const PROMISE_STATUS_FULFILLED = 'fulfilled'
const PROMISE_STATUE_REJECTED = 'rejected'
class XYPromise {
constructor(executor) {
this.status = PROMISE_STATUS_PEDDING
this.vaule = undefined
this.reason = undefined
this.onFulfilledFns = []
this.onRejectedFns = []
const resolve = (value) => {
if (this.status === PROMISE_STATUS_PEDDING) {
queueMicrotask(()=>{
this.status = PROMISE_STATUS_FULFILLED
this.value = value
this.onFulfilledFns.forEach(fn=>{
fn(this.value)
})
})
}
}
const reject = (reason) => {
if (this.status === PROMISE_STATUS_PEDDING) {
queueMicrotask(()=>{
this.status = PROMISE_STATUE_REJECTED
this.reason = reason
this.onRejectedFns .forEach(fn=>{
fn(this.reason)
})
})
}
}
executor(resolve, reject)
}
then(onFulfilled,onRejected){
this.onFulfilledFns.push(onFulfilled)
this.onRejectedFns .push(onRejected)
}
}
const promise = new XYPromise((resolve, reject) => {
console.log('pedding')
resolve("resolve message")
// reject("reject message")
})
promise.then(res => {
console.log("res1:", res)
}, err => {
console.log("err1:", err)
})
promise.then(res => {
console.log("res2:", res)
}, err => {
console.log("err2:", err)
})
手写promise-then方法(简单实现)
最新推荐文章于 2024-03-06 17:18:37 发布