JS手写-Promise

151 阅读1分钟
class MyPromise{
    constructor(fn){
        this.state = 'pending';
        this.value = '';

        this.resolvedCallbacks = [];
        this.rejectedCallbacks = [];

        //将 MyPromise 实例对象的 resolve 和 reject 的 this 指向 MyPromise
        fn(this.resolve.bind(this),this.reject.bind(this))
    }

    //将状态 pending 改为 fulfilled
    resolve(value){
        if(this.state === 'pending'){
            this.state = 'fulfilled';
            this.value = value;

            //执行成功回调的所有函数
            this.resolvedCallbacks.map(cb => cb(value))
        }
    }

    //将状态 pending 改为 reject
    reject(value){
        if(this.state === 'pending'){
            this.state = 'rejected';
            this.value = value;

            //执行失败回调的所有函数
            this.rejectedCallbacks.map(cb => cb(value))   
        }
    }

    then(onResolved,onRejected){
        //成功状态
        if(this.state === 'fulfilled'){
            onResolved(this.value)
        }
        //失败状态
        if(this.state === 'rejected'){
            onRejected(this.value)
        }
        //进行中状态(异步操作)
        if(this.state === 'pending'){
            // 将回调函数 push 到对应数组中
            this.resolvedCallbacks.push(onResolved);
            this.rejectedCallbacks.push(onRejected);
        }
    }

}