手写实现Promise

106 阅读1分钟

手写promise,会提升你对promise的理解深度,也会提高对js代码的处理能力。如果对一个概念不明白,或者虽然理解但是却讲不出明确的概念的话,很明显,你对这个概念不够熟悉,如果想提高,那最好的方法,就是手写一遍。

以下内容是本人学习手写promise的过程对思路的整理,和自己的理解

先来个简单版的promise

        //三个状态值
        const pending = 'pending'
        const fulfilled = 'fulfilled'
        const rejected = 'rejected'
        class myPromise {
            constructor(callback) {
                //初始化为pending
                this.status = pending
                //执行成功的值
                this.reason = undefined
                //执行失败的值
                this.value = undefined
                //成功执行的函数
                const resolve = (res) => {
                    if (this.status === pending) {
                        this.status = fulfilled
                        this.value = res
                    }
                }
                //失败执行的函数
                const reject = (err) => {
                    if (this.status === pending) {
                        this.status = rejected
                        this.reason = err
                    }
                }
                try {
                    //调用myPromise的回调函数
                    callback(resolve, reject)
                } catch (err) {
                    reject(err)
                }
            }
            then(success, failed) {
                if (this.status === fulfilled) {
                    success(this.value)
                }
                if (this.status === rejected) {
                    failed(this.reason)
                }
              
            }
        }