实现一个promise

106 阅读5分钟

1.用class实现

    class MPromise {
        constructor() {
        }
    }

2.定义三种状态

    const PENGING = 'PENGING';
    const FULFILLED = 'FULFILLED';
    const REFECTED = 'REFECTED'

3.设置初始状态

    class MPromise {
        constructor() {
            //设置初始状态
            this.status = PENDING;
            this.value = null;
            this.reason = null;
        }
    }

4.resolve方法和reject方法

    class MPromise {
        constructor() {
            //设置初始状态
            this.status = PENDING;
            this.value = null;
            this.reason = null;
        }
        
        resolve(value) {
            if(this.status === PENDING){
                this.status = FULFILLED;
                this.value = value;
            }
        }
        reject(reason) {
            if(this.status === PENDING) {
                this.status = REJECTED;
                this.reason = reason;
            }
        }
    }

5.添加promise的入参

入参是一个函数;函数接收resolve、reject两个参数 在初始化promise的时候,就要执行这个函数,并且有任何报错都要通过reject抛出去

    class MPromise {
        constructor(fn) {
            //设置初始状态
            this.status = PENDING;
            this.value = null;
            this.reason = null;
            
            try {
                fn(this.resolve.bind(this), this.reject.bind(this));
            } cath (e) {
                this.rejece(e);
            }
        }
        
        resolve(value) {
            if(this.status === PENDING){
                this.status = FULFILLED;
                this.value = value;
            }
        }
        reject(reason) {
            if(this.status === PENDING) {
                this.status = REJECTED;
                this.reason = reason;
            }
        }
    }

6.实现关键的then方法

then方法接受两个参数,onFulfilled和onRejected

    then(onFulfilled, onRejected) {}

检查并处理参数,如果不是function,就原样返回value或者reason

    isFunction(fn) {
        return typeof fn === 'function'
    }
    
    then(onFulfilled, onRejected) {
        const realOnFulfilled = this.isFunction(onFulfilled) ? onFulfilled : (value) =>{
            return value
        }
        
        const realOnRejected = this.isFunction(onRejected) ? onRejected : (reason) => {
            throw reason
        }
    }

.then方法返回的是一个promise;

    then(onFulfilled, onRejected) {
        const realOnFulfilled = this.isFunction(onFulfilled) ? onFulfilled : (value) =>{
            return value
        }
        
        const realOnRejected = this.isFunction(onRejected) ? onRejected : (reason) => {
            throw reason
        }
        
        const promise2 = new MPromise((resolve, reject) => {

        })
        return promise2
    }
    
    

根据当前promise的状态,调用不同的函数

    then(onFulfilled, onRejected) {
        const realOnFulfilled = this.isFunction(onFulfilled) ? onFulfilled : (value) =>{
            return value
        }
        
        const realOnRejected = this.isFunction(onRejected) ? onRejected : (reason) => {
            throw reason
        }
        
        const promise2 = new MPromise((resolve, reject) => {
            swicth (this.stauts) {
                case FULFILLED: {
                    realOnFulfilled()
                    break
                }
                case REJECTED: {
                    realOnRejected()
                    break
                }
            }
        })
        return promise2
    }
    
    

如果调用then函数时status还是在pending状态时添加一个状态监听机制当状态变为fulfilled和rejected后再去执行callback 那么首先要拿到所有的callback,然后在某个时机去执行他,新建两个数组分别储存成功和失败的回调,在调用then时候,如果还是pending就存入数组中;

    FULFILLED_CALLBACK_LIST = [];
    REJECTED_CALLBACK_LIST = [];
    then(onFulfilled, onRejected) {
        const realOnFulfilled = this.isFunction(onFulfilled) ? onFulfilled : (value) =>{
            return value
        }
        
        const realOnRejected = this.isFunction(onRejected) ? onRejected : (reason) => {
            throw reason
        }
        
        const promise2 = new MPromise((resolve, reject) => {
            swicth (this.stauts) {
                case FULFILLED: {
                    realOnFulfilled()
                    break
                }
                case REJECTED: {
                    realOnRejected()
                    break
                }
                case PENDING: {
                    this.FULFILLED_CALLBACK_LIST.push(realOnFulfilled)
                    this.REJECTED_CALLBACK_LIST.push(realOnRejected)
                }
            }
        })
        return promise2
    }
    

在status发生变化的时候,就执行所有的回调,这里用es6的getter和setter,这样更符合语义,当status改变时,去做什么事情

    _status = PENDING;
    
    get status() {
        return this._status;
    }
    
    set status(newStatus) {
        this._status = newStatus;
        switch (newStatus) {
            case FULFILLED: {
                this.FULFILLED_CALLBACK_LIST.forEach(callback => {
                    callback(this.value);
                });
                break;
            }
            case REJECTED: {
                this.REJECTED_CALLBACK_LIST.forEach(callback => {
                    callback(this.reason);
                })
                break;
            }
        }
    }

7.then的返回值

前面只是简单说了一下,then的返回值是一个Promise,那么接下来具体实现;一下promise的value和reason是什么;;如果onFilfilled或者onRejected抛出一个异常e,则promise2必须拒绝执行,并返回e;

    then(onFulfilled, onRejected) {
        const realOnFulfilled = this.isFunction(onFulfilled) ? onFulfilled : (value) =>{
            return value
        }
        
        const realOnRejected = this.isFunction(onRejected) ? onRejected : (reason) => {
            throw reason
        }
        
        const promise2 = new MPromise((resolve, reject) => {
            const fulfilledMicrotask = () => {
                try {
                    realOnFulfilled(this.value);
                } catch (e) {
                    reject(e)
                }
            }
            
            const rejeceedMicrotask = () => {
                try {
                    realOnRejected(this.reason)
                } catch (e) {
                    reject(e)
                }
            }
            
            swicth (this.stauts) {
                case FULFILLED: {
                    fulfilledMicrotask()
                    break
                }
                case REJECTED: {
                    rejeceedMicrotask()
                    break
                }
                case PENDING: {
                    this.FULFILLED_CALLBACK_LIST.push(fulfilledMicrotask)
                    this.REJECTED_CALLBACK_LIST.push(rejectedMicrotask)
                }
            }
        })
        return promise2
    }
    
    

如果onFulfilled 或者 onRejected 返回一个值x,则运行resolvePromise方法

    then(onFulfilled, onRejected) {
        const realOnFulfilled = this.isFunction(onFulfilled) ? onFulfilled : (value) =>{
            return value
        }
        
        const realOnRejected = this.isFunction(onRejected) ? onRejected : (reason) => {
            throw reason
        }
        
        const promise2 = new MPromise((resolve, reject) => {
            const fulfilledMicrotask = () => {
                try {
                    const x = realOnFulfilled(this.value);
                    this.resolvePromise(promise2, x, resolve, reject);
                } catch (e) {
                    reject(e)
                }
            }
            
            const rejeceedMicrotask = () => {
                try {
                     const x = realOnRejected(this.reason);
                     this.resolvePromise(promise2, x, resolve, reject);
                } catch (e) {
                    reject(e)
                }
            }
            
            swicth (this.stauts) {
                case FULFILLED: {
                    fulfilledMicrotask()
                    break
                }
                case REJECTED: {
                    rejeceedMicrotask()
                    break
                }
                case PENDING: {
                    this.FULFILLED_CALLBACK_LIST.push(fulfilledMicrotask)
                    this.REJECTED_CALLBACK_LIST.push(rejectedMicrotask)
                }
            }
        })
        return promise2
    }
    
    

8.实现resolvePromise

    resolvePromise (promise2, x, resolve, reject) {
        //如果newPromise 和 x 指向同一对象,以 TypeError 拒绝执行 newPromise
        //为了防止死循环
        if (promise2 === x) {
            return reject(new TypeError('The promise and the return value are the same'))
        }
        
        if(x instanceof MPromise) {
            //如果x为 Promise,则使 newPromise 接受x的状态
            //也就是继续执行x,如果执行的时候拿到一个y,还要继续解析y
            queueMicrotask(() => {
                x.then((y) => {
                    this.resolvePromise(promise2, y, resolve, reject);
                }, reject)
            })
        } else if (typeof x === 'object' || this.isFunction(x)) {
            //如果 x 为对象或者函数
            if (x === null) {
                //null 也会被判断为对象
                return resolve(x)
            }
            let then = null;
            
            try {
                //吧 x.then 赋值给 then
                then = x.then;
            } catch (error) {
                //如果 x.then 的值时抛出错误e ,则以e 为据因 拒绝promise
                return reject(error);
            }
            
            //如果then是函数
            if (this.isFunction(then)) {
                let called = false;
                //将x 作为函数的作用域 this 调用
                //传递两个回调函数作为参数,第一个参数叫做 resolvePromise, 第二个参数叫做 rejectPromise
                try {
                    then.call(
                    x,
                    //如果 resolvePromise 以值 y 为参数被调用, 则运行resolvePromise
                    (y) => {
                        //需要有一个变量called来保证只调用一次
                        if(called) return;
                        calld = true;
                        this.resolvePromise(promise2, y, resolve, reject);
                    }, 
                    //如果 rejectPromise 以r 为参数被调用,以r拒绝promise
                    (r) => {
                        if (called) return;
                        called = true;
                        reject(r);
                    })
                } catch (error) {
                    //如果调用 then 方法抛出了异常 e;
                    if (called) return;
                    refect(error);
                }
            } else {
                //如果then不是函数,以 x 为参数执行 promise
                resolve(x)
            }
        } else {
            //如果 x 不为对象或者函数,以 x 为参数执行 promise
            resolve(x);
        }
    }

9.onFulfilled 和 onRefected 是微任务,用queueMicrotask包裹执行函数

    const fulfilledMicrotask = () => {
        queueMicrotask(() => {
            try {
                const x = realOnFulfilled(this.value);
                this.resolvePromise(promise2, x, resolve, reject);
            } catch (e) {
                reject(e)
            }
        })
    };
    const rejectedMicrotask = () => {
        queueMicrotask(() => {
            try {
                const x = realOnRejected(this.reason);
                this.resolvePromise(promise2, x, resolve, reject);
            } catch (e) {
                reject(e);
            }
        })
    }

10.catch 方法

    catch (onRejected) {
        return this.then(null,onRejected);
    }

11.promise.resolve

将现有对象转为Promise对象,如果Promise.resolve方法的参数,不是具有 then 方法的对象(又称thennable对象),则返回一个新的Promise对象,且它的状态为 fulfilled。 注意这是一个静态方法,是通过Promise.resolve调用的,而不是通过实例去调用的;

    static resolve(value) {
        if (value instanceof MPromise) {
            return value;
        }
        
        return new MPromise((resolve) => {
            resolve(value);
        })
    }
    

12.promise.reject

返回一个新的Promise实例,该实例的状态为rejected;Promise.reject方法的参数reason,会被传递给实例的回调函数。

    static reject(reason) {
        return new MPromsie((resolve,reject) => {
              reject(reson)
        })
    }
    

13.promise.rase

    const p = Promise.rase([p1, p2, p3])
    

该方法是将多个Promise实例,包装成一个新的Promise实例。 只要p1, p2, p3,之中有一个实例率先改变状态,p的状态就跟着改变。那个率先改变的Promise实例的返回值,就传递给p的回调函数。

    static race(promiseList) {
        const length = promsieList.length;
        
        if(length === 0) {
            return resolve()
        } else {
            for (let i = 0; i<length; i++) {
                MPromise.resolve(promiseList[i]).then(
                (value) => {
                    return resolve(value);
                },
                (reason) => {
                    return reject(reason)
                })
            }
        }
            
        
    }