实现一个基本的Promise

思路

未添加异步处理等其他边界情况 ①自动执行函数,②三个状态,③then

class Promise {
    constructor(fn) {
        // 添加三个状态
        this.state = 'pending'
        this.value = undefined
        this.reason = undefined

        let resolve = value => {
            if (this.state === 'pending') {
                this.state = 'fulfilled'
                this.value = value
            }
        }

        let reject = value => {
            if (this.state === 'pending') {
                this.state = 'rejected'
                this.value = value
            }
        }

        try {
            fn(resolve, reject)
        } catch (e) {
            reject(e)
        }
    }

    then(onFullfilled, onRejected) {
        switch (this.state) {
            case "fulfilled":
                onFullfilled()
                break
            case "rejected":
                onRejected()
                break
            default :
        }
    }
}

发布了13 篇原创文章 · 获赞 12 · 访问量 1436

猜你喜欢

转载自blog.csdn.net/weixin_44014980/article/details/104526123
今日推荐