本文最后更新于233 天前,其中的信息可能已经过时,如有错误请发送邮件到1986413837@qq.com
1.构造器
const PENDING = "pending"
const FULFILLED = "fulfilled"
const REJECTED = "rejected"
class MyPromise {
#state = PENDING
#value = undefined
constructor(executor) {
const resolve = (val) => {
this.#setState(FULFILLED, val)
}
const reject = (reason) => {
this.#setState(REJECTED, reason)
}
try {
executor(resolve, reject)
}
catch (err) {
reject(err)
}
}
#setState(state, value) {
if (this.#state !== PENDING) return
this.#value = value
this.#state = state
console.log(this.#state, this.#value)
}
}
const p = new MyPromise((resolve, reject) => {
reject(2)
resolve(1)
})
2.Promise.then()
const PENDING = "pending"
const FULFILLED = "fulfilled"
const REJECTED = "rejected"
function isPromiseLike(obj) {
return typeof obj?.then === 'function'
}
class MyPromise {
#state = PENDING
#value = undefined
#handlers = []
constructor(executor) {
const resolve = (val) => {
this.#setState(FULFILLED, val)
}
const reject = (reason) => {
this.#setState(REJECTED, reason)
}
try {
executor(resolve, reject)
}
catch (err) {
reject(err)
}
}
#setState(state, value) {
if (this.#state !== PENDING) return
this.#value = value
this.#state = state
this.#runTask()
}
#runTask() {
queueMicrotask(() => {
if (this.#state !== PENDING) {
this.#handlers.forEach((cb) => cb())
this.#handlers = []
}
})
}
then(onFulfilled, onRejected) {
return new MyPromise((resolve, reject) => {
this.#handlers.push(() => {
try {
const cb = this.#state === FULFILLED ? onFulfilled : onRejected
const res = typeof cb === 'function' ? cb(this.#value) : this.#value
if (isPromiseLike(res)) {
res.then(resolve, reject)
}
else {
resolve(res)
}
} catch (error) {
reject(error)
}
})
this.#runTask()
})
}
}