手写Promise

class P {
    // 定义promise的三个静态属性
    static pedding = 'pedding';
    static fulfilled = 'fulfilled';
    static rejected = 'rejected';

    constructor(fn) {
        // 初始状态为pedding
        this.status = P.pedding;
        // 返回的结果先定义为null,随后要进行赋值
        this.result = null;
        // 为了解决异步的
        this.successCallback = [];
        this.failedCallback = [];
        // 利用错误捕获,实现throw err的功能
        try {
            // 利用bind绑定this, 解决this丢失的问题
            fn(this.resolve.bind(this), this.reject.bind(this));
        }
        catch (error) {
            this.reject(error);
        }
    }

    resolve(result) {
        setTimeout(() => {
            if (this.status === P.pedding) {
                this.status = P.fulfilled;
                this.result = result;
                this.successCallback.forEach(callback => {
                    callback(result);
                });
            }
        });
    }

    reject(result) {
        setTimeout(() => {
            if (this.status === P.pedding) {
                this.status = P.rejected;
                this.result = result;
                this.failedCallback.forEach(callback => {
                    callback(result);
                });
            }
        });
    }

    then(onSuccess, onFailed) {
        // return一个新的Promise实现链式调用
        return new P((resolve, reject) => {
            onSuccess = typeof onSuccess === 'function' ? onSuccess : () => {};
            onFailed = typeof onFailed === 'function' ? onFailed : () => {};
            if (this.status === P.pedding) {
                this.successCallback.push(onSuccess);
                this.failedCallback.push(onFailed);
            }
            if (this.status === P.fulfilled) {
                setTimeout(() => {
                    onSuccess(this.result);
                });
            }
            if (this.status === P.rejected) {
                setTimeout(() => {
                    onFailed(this.result);
                });
            }
        });
    }
}