编辑代码

class CcPromise {
    constructor(fn) {
        // 定义状态,默认为pending
        this.state = 'pending';
        // 定义resolve/reject的返回值
        this.value = '';
        // 定义resolve时的回调函数集合
        this.resolveCallbacks = [];
        // 定义reject时的回调函数集合
        this.rejectCallbacks = [];
        // 定义resolve函数
        this.resolve = (value) => {
            if (this.state === 'pending') {
                this.state = 'fulfilled';
                this.value = value;
                this.resolveCallbacks.forEach(fn => fn());
            } 
        };
        this.reject = (value) => {
            if (this.state === 'pending') {
                this.state = 'rejected';
                this.value = value;
                this.rejectCallbacks.forEach(fn => fn());
            } 
        };
        try {
            fn(this.resolve, this.reject);
        } catch (e) {
            this.reject(e);
        }
    }
    then(resolve, reject) {
        if (this.state === 'fulfilled') {
            resolve(this.value);
        }
        if (this.state === 'rejected') {
            reject(this.value);
        }
        if (this.state === 'pending') {
            this.resolveCallbacks.push(() => {
                resolve(this.value);
            });
            this.rejectCallbacks.push(() => {
                resolve(this.value);
            });
        }
    }
}
const p = () => new CcPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('You so good, just go ahead!')
    }, 1000)
});
p().then(res => { console.log(res) });