手写一个简易版的Promise

129 阅读1分钟
class MyPromise {
    // 1.1 定义promise的状态
    static STATUS = {
        PENDING: 'pending',
        FULFILLED: 'fulfilled',
        REJECTED: 'rejected',
    };
    // 1.2 实例私有属性,不许更改
    #status = '';
    // 1.3 构造器
    constructor(func) {
        this.#status = MyPromise.STATUS.PENDING; // 1.3.1 初始化私有属性
        this.value = null; // 1.3.2 resolve的结果
        this.reason = null; // 1.3.3 reject的结果

        // 5.2 创建保存resolve和reject后的回调函数
        this.resolveCallbacks = []; // 在待定状态下,保存resolve函数
        this.rejectCallbacks = []; // 在待定状态下,保存reject函数

        // 3.1 如果执行器函数抛出错误,原生promise会执行reject方法
        try {
            // 1.3.4 bind用于给this绑定为当前的实例对象
            func.call(
                undefined,
                this.resolve.bind(this),
                this.reject.bind(this)
            ); // 执行传进来的函数
        } catch (error) {
            this.reject(error);
        }
    }

    // 2.1 创建resolve函数
    resolve(result) {
        setTimeout(() => {
            // 2.1.1 待定状态后来改变状态和 resolve结果 value
            if (this.#status === MyPromise.STATUS.PENDING) {
                this.#status = MyPromise.STATUS.FULFILLED;
                this.value = result;
                this.resolveCallbacks.forEach(callback => {
                    callback(result);
                });
            }
        });
    }

    // 2.2 创建reject函数
    reject(result) {
        setTimeout(() => {
            // 2.2.1 待定状态后来改变状态和 reject结果 reason
            if (this.#status === MyPromise.STATUS.PENDING) {
                this.#status = MyPromise.STATUS.REJECTED;
                this.reason = result;
                this.rejectCallbacks.forEach(callback => {
                    callback(result);
                });
            }
        });
    }

    // 2.3 创建reject函数
    then(onFULFILLED, onREJECTED) {
        // 6.1 实现无限链式 - 返回一个新promise
        return new MyPromise((resolve, reject) => {
            // 3.2 如果两个参数不是函数,原生promise不会报错
            // 所以这里我们处理一下
            onFULFILLED =
                typeof onFULFILLED === 'function' ? onFULFILLED : () => {};
            onREJECTED =
                typeof onREJECTED === 'function' ? onREJECTED : () => {};
            // 5.1 then中如果待定,保存传进来根据resolve和reject结果的回调
            if (this.#status === MyPromise.STATUS.PENDING) {
                this.resolveCallbacks.push(onFULFILLED);
                this.rejectCallbacks.push(onREJECTED);
            }
            if (this.#status === MyPromise.STATUS.FULFILLED) {
                // 4.1 setTimeout用来模拟原生then是异步的
                setTimeout(() => {
                    onFULFILLED(this.value);
                });
            }
            if (this.#status === MyPromise.STATUS.REJECTED) {
                // 4.2 setTimeout用来模拟原生then是异步的
                setTimeout(() => {
                    onREJECTED(this.reason);
                });
            }
        });
    }
}