使用 class 手写一个 Promise

295 阅读1分钟
        //创建一个 Promise 的类

        class Promise {

            constructor(executer) {//构造函数 constructor 里面是个执行器

                this.status = 'pending';//默认的状态 pending

                this.value = undefined//成功的值默认 undefined

                this.reason = undefined//失败的值默认 undefined

                //状态只有在 pending 时候才能改变

                let resolveFn = value => {
                    //判断只有等待时才能 resolve 成功
                    if (this.status == pending) {
                        this.status = 'resolve';
                        this.value = value;
                    }
                }

                //判断只有等待时才能 reject 失败
                let rejectFn = reason => {

                    if (this.status == pending) {

                        this.status = 'reject';

                        this.reason = reason;

                    }

                }

                try {

                    //把 resolve 和 reject 两个函数传给执行器 executer

                    executer(resolve, reject);

                } catch (e) {

                    reject(e);//失败的话进 catch

                }

            }

            then(onFufilled, onReject) {

                //如果状态成功调用 onFufilled

                if (this.status = 'resolve') {

                    onFufilled(this.value);

                }

                //如果状态失败调用 onReject

                if (this.status = 'reject') {

                    onReject(this.reason);

                }

            }

        }