promise pollyfill

95 阅读1分钟
;(function(){
    // 定义三种状态
    const status = {
        pending: 0, /*进行时*/
        fulfilled: 1, /*成功*/
        rejected: 2 /*失败*/
    }

    class CustomePromise {
        constructor(func){
            // 初始状态
            this._status = status.pending
            this._value = null;  // 记录resolve函数传入的参数
			this._error = null;  // 记录reject函数传入的参数

            this._handler(func)
        }

        // 接收外部传入的函数,调用外部传入的函数
        _handler(func){
            let done = false // 就是让函数值执行一次
            func(
                (value) => {
                    if( done ) return
                    done = true
                    // console.log(value)
                    this._resolve(value)
                },
                (error) => {
                    if( done ) return
                    done = true
                    // console.log(error)
                    this._reject(error)
                }
            )
        }

        _resolve(){
            // 把状态改为成功,状态不可逆
            this._status = status.fulfilled
        }

        _reject(){
            // 把状态改为失败,状态不可逆
            this._status = status.rejected
        }
    }

    window.CustomePromise = CustomePromise
})()