美文网首页
手写极简版promise

手写极简版promise

作者: 小螃蟹_5f4c | 来源:发表于2020-04-23 15:54 被阅读0次

    为了更更加好的理解promise ,简单的学习了一下手写promise。
    于是我就简单的学了一下 ,首先分步操作,
    先实现基础部分,不考虑链式调用,

    function myPromise(executor) {
        var _this = this;
        this.state = 'pending';
        this.value = undefined;
        this.reason = undefined;
        this.onFulfilledFunc = [];//保存成功回调
        this.onRejectedFunc = [];//保存失败回调
        //其它代码略...
     function resolve(value) {
            //当状态为pending时再做更新
            if (_this.state === 'pending') {
                _this.value = value;//保存成功结果
                _this.state = 'resolved';
            }
    
        }
    
        function reject(reason) {
        //当状态为pending时再做更新
            if (_this.state === 'pending') {
                _this.reason = reason;//保存失败原因
                _this.state = 'rejected';
            }
        }
    //这里执行promise传入的函数部分
    try {
            executor(resolve, reject); //马上执行
                } 
    catch (error) {
                    reject(error)
                }
    }
    

    then方法的实现
    当myPromise的状态发生了改变,不论是成功或是失败都会调用then方法,所以,then方法的实现也很简单,根据state状态来调用不同的回调函数即可,但是由于执行的时候可能状态还是pending 所以执行的时候如果是pending 我们则把传入的成功和失败的回调函数传入callback数组里面 等resolve函数里面去执行

    myPromise.prototype.then = function (onFulfilled, onRejected) {
        //等待态,此时异步代码还没有走完
        if (this.state === 'pending') {
            if (typeof onFulfilled === 'function') {
                this.onFulfilledFunc.push(onFulfilled);//保存回调
            }
            if (typeof onRejected === 'function') {
                this.onRejectedFunc.push(onRejected);//保存回调
            }
        }
        //其它代码略...
    }
    

    链式调用
    romise处理异步代码最强大的地方就是支持链式调用,这块也是最复杂的,我们先梳理一下规范中是怎么定义的:
    每个then方法都返回一个新的Promise对象(原理的核心)
    如果then方法中显示地返回了一个Promise对象就以此对象为准,返回它的结果
    如果then方法中返回的是一个普通值(如Number、String等)就使用此值包装成一个新的Promise对象返回。
    如果then方法中没有return语句,就视为返回一个用Undefined包装的Promise对象
    若then方法中出现异常,则调用失败态方法(reject)跳转到下一个then的onRejected
    如果then方法没有传入任何回调,则继续向下传递(值的传递特性)。
    看起来抽象 代码解释看下面简书博客
    resolve 和reject的改造:
    对于 resolve 函数来说,首先需要判断传入的值是否为 Promise 类型
    为了保证函数执行顺序,需要将两个函数体代码使用 setTimeout 包裹起来

    function resolve(value) {
                    // 对于 resolve 函数来说,首先需要判断传入的值是否为 Promise 类型
                    if (value instanceof myPromise) {
                        return value.then(resolve, reject)
                    }
                    setTimeout(() => {
                        if (_this.state = 'pending') {
                            _this.value = value;
                            _this.onFullfiledCallBack.forEach(fn => fn(value));
                            _this.state = 'resolved';
                        }
                    }, 0)
    
                }
                function reject(reason) {
                    setTimeout(() => {
                        if (_this.state = 'pending') {
                            _this.reason = reason;
                            _this.onRejectCallBack.forEach(fn => fn(value));
                            _this.state = 'rejected';
                        }
                    }, 0)
    
                }
    

    接下来改造的then代码:

    myPromise.prototype.then = function (onFullfiled, onRejected) {
                let self = this;
                let promise2 = null;
                onFullfiled = typeof onFullfiled === 'function' ? onFullfiled : v => v;
                onRejected = typeof onRejected === 'function' ? onRejected : r => { throw r };
                if (this.state == 'pending') {
                    return (promise2 = new myPromise((resolve, reject) => {
                        self.onFullfiledCallBack.push(() => {
                            try {
                                let x = onFullfiled(self.value);
                                //处理then不同的返回值和下面传递链的传递方式
                                resolutionProduce(promise2, x, resolve, reject);
                            } catch (e) {
                                reject(e)
                            }
                        });
                        self.onRejectCallBack.push(() => {
                            try {
                                let x = onRejected(self.value);
                                resolutionProduce(promise2, x, resolve, reject);
                            } catch (e) {
                                reject(e)
                            }
                        })
                    }))
                }
            }
    

    思路跟之前基本一致,只是说把之前返回值改成promise,同时捕获异常,在status状态为FULFILLED或者REJECTED的时候执行得加上异步setTimeout包裹。 接下来完成最核心的resolutionProduce函数:

    function resolutionProduce(promise, x, resolve, reject) {
                if (promise === x) {
                    reject(new TypeError('error'))
                }
                if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
                    // 可能是个对象或者函数
                    try {
                        let then = x.then;
                        if (typeof then === 'function') {
                            //取出的then是函数,那么执行函数 ,就将x作为函数的作用域 this 调用之,并且传递两个回调函数作为参数,第一个参数叫做 resolvePromise ,第二个参数叫做 rejectPromise
                            let y = then.call(x, y => {
                                //递归调用
                                resolutionProduce(promise, y, resolve, reject);
                            }, r => reject(r))
                        } else {
                            resolve(x);
                        }
                    } catch (error) {
                        reject(error)
                    }
                } else {
                    //可能是普通值
                    resolve(x); //把第一个then的返回值传递给返回的promise值里面的then函数
                }
    
            }
    

    然后判断 x 是否为对象或者函数,如果都不是的话,将 x 传入 resolve 中
    如果 x 是对象或者函数的话,先把 x.then 赋值给 then,然后判断 then 的类型,如果不是函数类型的话,就将 x 传入 resolve 中
    如果 then 是函数类型的话,就将 x 作为函数的作用域 this 调用之,并且传递两个回调函数作为参数,第一个参数叫做 resolvePromise ,第二个参数叫做 rejectPromise,如果Promise对象转为成功态或是失败时传入的还是一个Promise对象,此时应该继续执行,直到最后的Promise执行完。所以递归操作(这一点我有点绕)
    以上代码在执行的过程中如果抛错了,将错误传入 reject 函数中

    最后极简版手写promise就完成了
    最后使用diamante验证:

    let p = new myPromise((resolve, reject) => {
                setTimeout(() => {
                    resolve('1')
                }, 1000)
            })
            p.then(data =>{
                console.log(data)
                return new myPromise((resolve,reject)=>{
                    setTimeout(()=>{
                        console.log('我是then里面打印出来的');
                        resolve('2222')
                    },1000)
                })
            } ).then(data=>console.log(data));
    

    能正确打印 结束!
    最终完整代码:

    function myPromise(executor) {
                let _this = this;
                this.state = 'pending';
                this.value = undefined;
                this.reason = undefined;
                this.onFullfiledCallBack = [];
                this.onRejectCallBack = [];
    
                function resolve(value) {
                    // 对于 resolve 函数来说,首先需要判断传入的值是否为 Promise 类型
                    if (value instanceof myPromise) {
                        return value.then(resolve, reject)
                    }
                    setTimeout(() => {
                        if (_this.state = 'pending') {
                            _this.value = value;
                            _this.onFullfiledCallBack.forEach(fn => fn(value));
                            _this.state = 'resolved';
                        }
                    }, 0)
    
                }
                function reject(reason) {
                    setTimeout(() => {
                        if (_this.state = 'pending') {
                            _this.reason = reason;
                            _this.onRejectCallBack.forEach(fn => fn(value));
                            _this.state = 'rejected';
                        }
                    }, 0)
    
                }
                try {
                    executor(resolve, reject); //马上执行
                } catch (error) {
                    reject(error)
                }
            }
            myPromise.prototype.then = function (onFullfiled, onRejected) {
                let self = this;
                let promise2 = null;
                onFullfiled = typeof onFullfiled === 'function' ? onFullfiled : v => v;
                onRejected = typeof onRejected === 'function' ? onRejected : r => { throw r };
                if (this.state == 'pending') {
                    return (promise2 = new myPromise((resolve, reject) => {
                        self.onFullfiledCallBack.push(() => {
                            try {
                                let x = onFullfiled(self.value);
                                //处理then不同的返回值和下面传递链的传递方式
                                resolutionProduce(promise2, x, resolve, reject);
                            } catch (e) {
                                reject(e)
                            }
                        });
                        self.onRejectCallBack.push(() => {
                            try {
                                let x = onRejected(self.value);
                                resolutionProduce(promise2, x, resolve, reject);
                            } catch (e) {
                                reject(e)
                            }
                        })
                    }))
                }
            }
            //处理then返回值如何传递和下一个then的值
            function resolutionProduce(promise, x, resolve, reject) {
                if (promise === x) {
                    reject(new TypeError('error'))
                }
                if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
                    // 可能是个对象或者函数
                    try {
                        let then = x.then;
                        if (typeof then === 'function') {
                            //取出的then是函数,那么执行函数 ,就将x作为函数的作用域 this 调用之,并且传递两个回调函数作为参数,第一个参数叫做 resolvePromise ,第二个参数叫做 rejectPromise
                            let y = then.call(x, y => {
                                //递归调用
                                resolutionProduce(promise, y, resolve, reject);
                            }, r => reject(r))
                        } else {
                            resolve(x);
                        }
                    } catch (error) {
                        reject(error)
                    }
                } else {
                    //可能是普通值
                    resolve(x); //把第一个then的返回值传递给返回的promise值里面的then函数
                }
    
            }
            let p = new myPromise((resolve, reject) => {
                setTimeout(() => {
                    resolve('1')
                }, 1000)
            })
            p.then(data =>{
                console.log(data)
                return new myPromise((resolve,reject)=>{
                    setTimeout(()=>{
                        console.log('我是then里面打印出来的');
                        resolve('2222')
                    },1000)
                })
            } ).then(data=>console.log(data));
    

    主要还是参考了几篇文章:
    https://www.jianshu.com/p/c633a22f9e8c
    https://blog.csdn.net/weixin_34348111/article/details/91374448
    https://segmentfault.com/a/1190000020505870

    相关文章

      网友评论

          本文标题:手写极简版promise

          本文链接:https://www.haomeiwen.com/subject/wweaihtx.html