Promise02 — 手写
本文最后更新于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()
        })
    }
}
Life's a struggle, I'll conquer it.
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇