promise原理:代码实现

基础代码

(function (window) {
    const PENDING = 'pending'
    const RESOLVED = 'resolved'
    const REJECTED = 'rejected'

    function Promise(excutor) {
        this._state = PENDING
        this._value = undefined
        this._callbacks = [];

        let _this = this;
        function resolve(value) {
            //这里面不能直接使用用this,因为不是在内部调用的,会改变this的指向
            if (_this.state !== PENDING) return ///多个resolved调用,保持仅有一个resolved函数有效
            _this._state = RESOLVED
            _this._value = value
            if (_this._callbacks.length) {
                setTimeout(_ => {
                    _this._callbacks.forEach(callback => {
                        callback.onResolved(value)
                    })
                }, 0)
            }
        }

        function reject(reason) {
            if (_this.state !== PENDING) return //多个reject调用,保持仅有一个reject函数有效
            _this._state = REJECTED
            if (_this._callbacks.length) {
                setTimeout(_ => {
                    _this._callbacks.forEach(callback => {
                        callback.onRejected(value)
                    })
                }, 0)
            }
        }
        try {
            excutor(resolve, reject)
        } catch (err) {
            reject(err);
        }
    }

    /**
     * 
     * @param {*} onResolved 
     * @param {*} onRejected 
     * 返回的promise的结果由 onResolved/onRejected 的执行结果决定
     */
    Promise.prototype.then = function (onResolved, onRejected) {
        //透传处理
        onResolved = typeof onResolved === 'function' ? onResolved : value => value
        onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }

        let _this = this;

        return new Promise((resolve, reject) => {
            function handle(callback) {
                try {
                    let result = callback(_this.value)
                    if (result instanceof Promise) {
                        result.then(resolve, reject)
                    } else {
                        resolve(result)
                    }
                } catch (err) {
                    reject(err)
                }
            }
            //处理三种状态PENDING/RESOLVED/REJECTED
            if (_this._state === PENDING) {
                _this._callbacks.push({
                    onResolved() {
                        handle(onResolved)
                    },
                    onRejected() {
                        handle(onRejected)
                    }
                })
            } else if (_this._state === RESOLVED) {
                //1.返回的是promise, resolve,reject
                //2.返回的是非promise
                //3.处理异常

                //立即异步执行
                setTimeout(_ => {
                    handle(onResolved)
                })
            } else {
                handle(onRejected)
            }
        })
    }
    Promise.prototype.catch = function (onRejected) {
        return this.then(undefined, onRejected)
    }
  
})(window)

静态方法

Promise.resolve/Promiss.reject

//返回一个失败状态的promise
Promise.reject = function (reason) {
    return new Promise((resolve, reject) => {
        reject(reason)
    })
}

Promise.resolve = function (value) {
    return new Promise((resolve, reject) => {
        if (value instanceof Promise) {
            value.then(resolve, reject)
        } else {
            resolve(value)
        }
    })
}

Promise.all的逻辑实现


/**
 * 
 * @param {*} promises promise的数组
 */
Promise.all = function (promises) {
    let values = new Array(promises.length);
    let resolveCount = 0;
    return new Promise((resolve, reject) => {
        promises.forEach((p, index) => {
            //Promise.resolve(p):把p统一处理成promise
            Promise.resolve(p).then(value => {
                resolveCount++;//成功的计数
                values[index] = value
                if (resolveCount === promises.length) {
                    resolve(values)
                }
            }, reason => {//有一个失败就整体失败
                reject(reason)
            })
        })
    })
}

Promise.race 的整体实现

Promise.race = function (promises) {
        return new Promise((resolve, reject) => {
            promises.forEach(p => {
                //Promise.resolve(p):把p统一处理成promise
                Promise.resolve(p).then(value => {
                    resolve(value)//有一个成功就整体失败
                }, reason => {//有一个失败就整体失败
                    reject(reason)
                })
            })
        })
    }

Promise.resolveDelay/Promoise.rejectDelay

Promise.resolveDelay = function (value, timeout) {
        return new Promise((resolve, reject) => {
            setTimeout(_ => {
                if (value instanceof Promise) {
                    value.then(resolve, reject)
                } else {
                    resolve(value)
                }
            }, timeout)
        })
    }

Promise.rejectDelay = function (reason, timeout) {
    return new Promise((resolve, reject) => {
        setTimeout(_ => {
            reject(reason)ð
        }, timeout)
    })
}

你可能感兴趣的:(前端,javascript,js,promise)