手写Promise的实现和心得

//This is javascript
class myPromise{
    constructor(executor){
        this.state = 'pending';
        this.value = null;
        this.reason = null;
        this.onFullfilledCallbacks = [];
        this.onRejectedCallbacks = [];

        let resolve = (value) => {
            if (this.state === 'pending') {
                this.value = value;
                this.state = 'fullfilled';
                this.onFullfilledCallbacks.forEach(fn => fn());
            }
        }

        let reject = (reason) => {
            if (this.state === 'pending') {
                this.state = 'rejected';
                this.reason = reason;
                this.onRejectedCallbacks.forEach(fn => fn());
            }
        }

        try{
            executor(resolve,reject)
        }catch(e) {
            reject(e);
        }
    }

    then(onFullfilled,onRejected) {
        // then函数的作用有两个
        // 1、返回一个promise,后面还可以继续.then,把回调记录在本身promise实例上面
        // 2、在promise的executor里面把订阅函数记录在callbacks当中,要么同步直接执行,要么异步由resolve来触发
        onFullfilled = typeof onFullfilled === 'function'?onFullfilled:value => value;
        onRejected = typeof onRejected === 'function'?onRejected:err => {throw err};
        let promise2 = new myPromise((resolve,reject) => {
            if (this.state === 'fullfilled') {
                setTimeout(() => {
                    try{
                        let x = onFullfilled(this.value);
                        // 这里是最核心的地方,需要解析then的fullfill函数的返回值,当前这个promise需要触发自己的resolve函数,才能让后面的then逻辑执行
                        // 如果是普通值,那么触发这里的resolve后面的就可以执行了,如果返回的本身也是一个promise,那就在当前的promise后面加一个then执行完之后来resolve当前的这个promise
                        this.resolvePromise(promise2,x,resolve,reject);
                    }catch(e) {
                        reject(e);
                    }
                },0);
            }

            if (this.state === 'rejected') {
                setTimeout(() => {
                    try{
                        let x = onRejected(this.reason);
                        this.resolvePromise(promise2,x,resolve,reject);
                    }catch(e) {
                        reject(e);
                    }
                },0);
            }

            if (this.state === 'pending') {
                this.onFullfilledCallbacks.push(() => {
                    setTimeout(() => {
                        try{
                            let x = onFullfilled(this.value);
                            this.resolvePromise(promise2,x,resolve,reject);
                        }catch(e) {
                            reject(e);
                        }
                    },0);
                })

                this.onRejectedCallbacks.push(() => {
                    setTimeout(() => {
                        try{
                            let x = onRejected(this.reason);
                            this.resolvePromise(promise2,x,resolve,reject);
                        }catch(e) {
                            reject(e);
                        }
                    },0);
                })
            }
        })
        return promise2;
    }

    resolvePromise(promise2,x,resolve,reject) {
        if (promise2 === x) {
            reject(new TypeError('circular reference'));
        }

        let called;
        if (x !== null && (typeof x === 'function' || typeof x === 'object')) {
            try{
                let then = x.then;
                if (typeof then === 'function') {
                    then.call(x,y => {
                        if (called) return;
                        called = true;
                        this.resolvePromise(promise2,y,resolve,reject);
                    },err => {
                        if (called) return;
                        called = true;
                        reject(err);
                    })
                }else {
                    if (called) return;
                    called = true;
                    resolve(x);
                }
            }catch(e) {
                if (called) return;
                called = true;
                reject(e);
            }
        }else {
            if (called) return;
            called = true;
            resolve(x);
        }
    }


    static resolve(value) {
        if (value instanceof myPromise) {
            return value;
        }

        return new myPromise((resolve,reject) => {
            resolve(value);
        })
    }

    static reject(value) {
        if (value instanceof myPromise) {
            return value;
        }

        return new myPromise((resolve,reject) => {
            reject(value);
        })
    }

    static all(promiseArray) {
        if (!Array.isArray(promiseArray)) {
            throw new TypeError('must be an array');
        }
        let result = [],
        i = 0;
        return new myPromise((resolve,reject) => {
            if (promiseArray.length === 0) {
                resolve(result);
            }else {
                promiseArray.forEach((pro,index) => {
                    if (pro instanceof myPromise) {
                        pro.then(value => {
                            result[index] = value;
                            i++;
                            if (i === promiseArray.length) {
                                resolve(result);
                            }
                        },err => {
                            reject(err);
                        })
                    }else {
                        result[index] = pro;
                        i++;
                        if (i === promiseArray.length) {
                            resolve(result);
                        }
                    }
                })
            }
        })
    }

    static race(promiseArray) {
        if (!Array.isArray(promiseArray)) {
            throw new TypeError('must be an array');
        }

        let flag = true;

        return new myPromise((resolve,reject) => {
            promiseArray.forEach(pro => {
                if (pro instanceof myPromise) {
                    pro.then(res => {
                        if (flag) {
                            flag = false;
                            resolve(res);
                        }
                    },err => {
                        if (flag) {
                            flag = false;
                            reject(err);
                        }
                    })
                }else {
                    if (flag) {
                        flag = false;
                        resolve(pro)
                    }
                }
            })
        })
    }
}

try{
    module.exports = myPromise;
}catch(e) {}

实现的逻辑和说明

上述代码基本上实现了所有的Promise/A+规范,实现了promise的静态resolve和reject方法,也实现了all和race方法。
1.onFullfilled那里,给了一个包装,如果不是方法的话,就称为一个参数为value,return value的方法,实现了值穿透
2.then里面的方法都是异步的,都要加settimeout
3.resolvePromise放在了对象里头,作为原型方法,要控制x的状态不可改动,所以外层加入called,只要执行了该promise的resolve或者reject,就不能够再改动
4.all方法就是把所有promise对象执行的结果,给result,然后外层的promise去resolve那个result即可
5.race方法,就是全部promise都执行then方法,then方法执行的时候,成功回调或者失败回调的时候会改掉flag,所以只有最先执行成功或者失败回调的那个promise的值会给外层的promise去resolve
6.resolvePromise方法,可以想象为外层的promise对象,用自己的resolve和reject一直在找返回值,如果返回值还是promise就继续往下递归,直到找到那个普通值,然后给resolve掉,不达目的不罢休

总结而言,实现promise还是有一点复杂的,其中涉及到this指向的细节解析then内部返回值的问题,代码大概200行,没有写注释,留此博客欢迎交流

这里记录一个promise的打印顺序,把前面提到的东西都加进去

new Promise((resolve, reject) => {
    console.log(1);
    setTimeout(() => {
        console.log(2);
        resolve(1)
    }, 3000)
}).then(res => {
    // 成功的回调
    console.log(3);
    return new Promise((resolve1) => {
        console.log(4);
        setTimeout(() => {
            console.log(5);
            resolve1()
        }, 3000)
    }).then(() => {
        // 其实这里的then会全部跑完才会resolve外面的
        console.log(6)
    })
}).then(() => {
    console.log(7)
})

上述的打印结果是1234567,如果then里面返回promise的话,会等promise所有都结束了之后才会resolve,这就是resolvePromise做的事情,因为他在最后一个promise后面加了一个then

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。