编辑代码


class myPromise {
    // 状态
    static PENDING = 'pending';
    static FULFILLED = 'fulfilled';
    static REJECTED = 'rejected';

    constructor(callback) {
        // 此时的状态
        this.PromiseState = myPromise.PENDING;
        this.PromiseResult = null;
        this.result = null;

        try {
            callback(this.resolve.bind(this), this.reject.bind(this));
        } catch(error) {
            this.reject(error)
        }

    }

    resolve(value) {
        if(this.PromiseState === myPromise.PENDING){
            this.PromiseState = myPromise.FULFILLED;
            this.result = value;
        }
    }

    reject(reason) {
        if(this.PromiseState === myPromise.PENDING){
            this.PromiseState = myPromise.REJECTED;
            this.result = reason;
        }
    }

    then(onFulfilled, onRejected) {
        // 检验参数
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
        onRejected = typeof onRejected === 'function' ? onRejected : reason => {
            throw reason;
        };
        
        // 成功
        if(this.PromiseState === myPromise.FULFILLED) {
            onFulfilled(this.result)
        }
        
        // 失败
        if(this.PromiseState === myPromise.REJECTED) {
            onRejected(this.result)
        }
    }

    catch() {

    }

}


const result = new myPromise((req, rej) => {
    // req('myPromise')
    // rej('失败了')
    throw new Error('白嫖不成功');
})
result.then((data) => {
    console.log('myPromise then onFulfilled--->', data);
}, (err) => {
    console.log('myPromise then onRejected--->', err);
})
// console.log(result);

// console.log('----------');

// const re = new Promise((req, rej) => {
//     req('22')
// }).then((data) => {
//     console.log('then--->', data)
// });
// console.log(re)