手写简单Promise实现

本文详细介绍了如何使用ES6的Promise封装异步操作,包括成功和失败回调函数的处理,以及then和catch方法的链式调用。重点展示了如何通过MyPromise类实现Promise的构造、状态管理和回调函数调度。
摘要由CSDN通过智能技术生成
function MyPromise(executor) {
    this.PromiseState = 'pending'
    this.PromiseResult = null
    this.callbacks = []
    const self = this;

    //成功函数
    function resolve(value) {
        if (self.PromiseState !== 'pending') return
        self.PromiseState = 'fulfilled'
        self.PromiseResult = value

        setTimeout(() => {
            self.callbacks.forEach(element => {
                element.onResolved(value)
            })
        });
    }
    //失败函数
    function reject(reson) {
        if (self.PromiseState !== 'pending') return
        self.PromiseState = 'rejected'
        self.PromiseResult = reson
        setTimeout(() => {
            self.callbacks.forEach(element => {
                element.onRejected(resolve)
            })
        });
    }
    try {
        executor(resolve, reject)
    } catch (e) {
        reject(e)
    }
}

//绑定then到原型链上
MyPromise.prototype.then = function (onResolved, onRejected) {
    if (typeof onRejected !== 'function') {
        onRejected = reson => {
            throw reson
        }
    }
    if (typeof onResolved !== 'function') {
        onResolved = value => value
    }

    //返回一个新的MyPromise方便以后链式调用
    return new MyPromise((resolve, reject) => {
        let self = this;
        function handle(callback) {
            try {
                let result = callback(self.PromiseResult)
                if (result instanceof MyPromise) {
                    result.then(v => {
                        resolve(v)
                    }, r => {
                        reject(r)
                    })
                } else {
                    resolve(result)
                }
            } catch (e) {
                reject(e)
            }
        }
        if (this.PromiseState == 'pending') {
            this.callbacks.push({
                onResolved(value) {
                    handle(onResolved)
                },
                onRejected(value) {
                    handle(onRejected)
                }
            })
        }

        if (this.PromiseState === 'fulfilled') {
            setTimeout(() => {
                handle(onResolved)
            });
        }

        if (this.PromiseState === 'rejected') {
            setTimeout(() => {
                handle(onRejected)
            });
        }
    })
}


//绑定catch到原型链上
MyPromise.prototype.catch = function (onRejected) {
    return this.then(undefined, onRejected)
}

Es6 Class

class MyPromise {
    constructor(executor) {
        this.PromiseState = 'pending' //执行状态
        this.reason = '' //错误信息
        this.PromiseResult = null //返回值
        this.callbacks = [] //函数组

        executor(this.resolve.bind(this), this.reject.bind(this))
    }

    //成功的回调
    resolve(value) {
        
        if (value instanceof MyPromise) {
            value.then(this.resolve.bind(this),this.reject.bind(this));
            return;
        }

        this.PromiseState = 'fulfilled'
        this.PromiseResult = value

        this.callbacks.forEach(callback => {
            this._handler(callback)
        })
    }
    //失败回调函数
    reject(reson) {

        if (reson instanceof MyPromise) {
            reson.then(this.resolve.bind(this),this.reject.bind(this));
            return;
        }

        this.PromiseState = 'rejected'
        this.PromiseResult = reson
        
        this.callbacks.forEach(callback => {
            this._handler(callback)
        })
    }

    then(onResolved, onRejected) {
        return new MyPromise((nextResolve, nextReject) => {
            // 这里之所以把下一个Promsie的resolve函数和reject函数也存在callback中
            // 是为了将onResolved的执行结果通过nextResolve传入到下一个Promise作为它的value值
            this._handler({
                nextResolve,
                nextReject,
                onResolved,
                onRejected
            });
        });
    }
    
    //失败函数
    catch(onRejected) {
        return this.then(undefined, onRejected)
    }

    _handler(callback) {
        const {
            onResolved,
            onRejected,
            nextResolve,
            nextReject
        } = callback;

        if (this.PromiseState === 'pending') {
            this.callbacks.push(callback);
            return;
        }

        if (this.PromiseState === 'fulfilled') {
            // 传入存储的值
            // 未传入onResolved时,value传入
            const nextValue = onResolved ? onResolved(this.PromiseResult) : this.PromiseResult;
            nextResolve(nextValue);
            return;
        }

        if (this.PromiseState === 'rejected') {
            // 传入存储的错误信息
            // 同样的处理
            const nextReason = onRejected ? onRejected(this.reason) : this.reason;
            nextReject(nextReason);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值