手写Promise基本结构

文章详细介绍了ES5中的Promise实现,包括状态管理、回调处理和基本方法如resolve/reject。随后对比了ES6中Promise的类封装方式,展示了构造函数、then/catch方法和静态方法如resolve/reject/all/race的使用。
摘要由CSDN通过智能技术生成

ES5

//1.promise有俩个属性
function PromiseDemo(callback) {
    //默认情况
    this.PromiseState = "pending"
    this.PromiseResult = undefined
    this.callbackFn = []
    const _resolve = function (value) {
        //让resolve或者reject只执行一个
        if (this.PromiseState !== "pending") return
        this.PromiseState = "fulfilled"
        this.PromiseResult = value
        this.callbackFn.forEach(item => {
            item.onFulfilled()
        })
    }.bind(this)

    const _reject = function (value) {
        //让resolve或者reject只执行一个
        if (this.PromiseState !== "pending") return
        this.PromiseState = "rejected"
        this.PromiseResult = value
        this.callbackFn.forEach(item => {
            item.onRejected()
        })
    }.bind(this)
    try {
        callback(_resolve, _reject)
    } catch (error) {
        this.PromiseState = "rejected"
        if (typeof (error) === 'object') {
            this.PromiseResult = error.message
            return
        }
        this.PromiseResult = error
    }
}

Object.assign(PromiseDemo.prototype, {

    then(onFulfilled, onRejected) {
        //当then无回调函数,自动添加回调函数
        if (!(onFulfilled instanceof Function)) {
            onFulfilled = value => value
        }

        if (!(onRejected instanceof Function)) {
            onRejected = reson => reson
        }
        return new PromiseDemo((resolve, reject) => {

            const _common = function (cb) {
                setTimeout(() => {

                    try {
                        const value = cb(this.PromiseResult)
                        if (value instanceof PromiseDemo) {
                            value.then((val => {
                                resolve(val)
                            }), reson => {
                                reject(reson)
                            })
                        } else {
                            resolve(value)
                        }
                    } catch (error) {
                        reject(error)
                    }


                })
            }
            if (this.PromiseState === "fulfilled") {
                //异步调用
                _common.call(this, onFulfilled)
            } else if (this.PromiseState === "rejected") {
                _common.call(this, onRejected)
            } else {
                this.callbackFn.push({
                    onFulfilled: _common.bind(this, onFulfilled),
                    onRejected: _common.bind(this, onRejected)
                })
            }
        })
    },
    catch(onRejected) {
        return this.then(undefined, onRejected)
    }
})

PromiseDemo.resolve = function (value) {

    if (value instanceof PromiseDemo) {
        return value
    } else {
        new PromiseDemo((resolve, reject) => {
            resolve(value)
        })
    }
}

PromiseDemo.reject = function (value) {
    return new PromiseDemo((resolve, reject) => {
        reject(value)
    })
}


PromiseDemo.all = function (array) {
    let arr = new Array(array.length);
    let i = 0
    return new PromiseDemo((resolve, reject) => {
        array.forEach((item, index) => {
            if (item.PromiseState === "fulfilled") {
                arr[index] = item.PromiseResult
                i++
                if (i === array.length) {
                    resolve(arr)
                }
            } else {
                reject(item.PromiseResult)
            }
        })
    })
}


PromiseDemo.race = function(array) {
    return new PromiseDemo((resolve,reject)=>{
        array.forEach(item=>{
            if(item.PromiseState == "fulfilled"){
                resolve(item.PromiseResult)
            }else {
                reject(item.PromiseResult)
            }
        })
    })
 }

ES6

class PromiseDemo {
    constructor(cb) {

        this.PromiseState = "pending"
        this.PromiseResult = undefined
        this.callbackFun = []
        const _resolve = value => {
            if (this.PromiseState !== "pending") return
            this.PromiseState = "fulfilled"
            this.PromiseResult = value
            this.callbackFun.forEach((item)=>{
               item.onFulfilled()
            })
        }

        const _reject = value => {
            if (this.PromiseState !== "pending") return
            this.PromiseState = "rejected"
            this.PromiseResult = value
            this.callbackFun.forEach((item)=>{
                item.onRejected()
            })
        }

        //调用执行函数
        try {
            cb(_resolve, _reject)
        } catch (error) {
            this.PromiseState = "rejected"
            this.PromiseResult = value
        }
    }

    then(onFulfilled, onRejected) {

        return new PromiseDemo((resolve, reject) => {

            const _common = (cb)=>{
                setTimeout(() => {
                    try {
                        let value = cb(this.PromiseResult)
                        if (value instanceof PromiseDemo) {
                            value.then((value) => {
                                resolve(value), reson => {
                                    reject(reson)
                                }
                            })
                        } else {
                            resolve(value)
                        }
                    } catch (error) {
                            reject(error)
                    }
                })
            }

            if (this.PromiseState === "fulfilled") {
                _common(onFulfilled)
                
            } else if (this.PromiseState === "rejected") {
                _common(onRejected)
            }else { 
                this.callbackFun.push({
                    onFulfilled:_common.bind(this,onFulfilled),
                    onRejected:_common.bind(this,onRejected)
                })
            }
        })
    }
    catch(onRejected) {
        return this.then(undefined, onRejected)
    }

    static resolve(){
        if (value instanceof PromiseDemo) {
            return value
        } else {
            new PromiseDemo((resolve, reject) => {
                resolve(value)
            })
        }
    }

    static reject(){
        return new PromiseDemo((resolve, reject) => {
            reject(value)
        })
    }

    static all(array) {
        let arr = new Array(array.length);
        let i = 0
        return new PromiseDemo((resolve, reject) => {
            array.forEach((item, index) => {
                if (item.PromiseState === "fulfilled") {
                    arr[index] = item.PromiseResult
                    i++
                    if (i === array.length) {
                        resolve(arr)
                    }
                } else {
                    reject(item.PromiseResult)
                }
            })
        })
     }

     static race(array) {
        return new PromiseDemo((resolve,reject)=>{
            array.forEach(item=>{
                if(item.PromiseState == "fulfilled"){
                    resolve(item.PromiseResult)
                }else {
                    reject(item.PromiseResult)
                }
            })
        })
      }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值