手撸一个promise【js】

class myPromise{
    static PENDING = "进行中";
    static RESOLVED = "完成";
    static REJECTED = "拒绝";
    constructor(func){
        //防止resolve被异步了,存储then的参数函数,等reslove完成再执行
        this.resStack = []
        this.rejStack = []

        this.status = myPromise.PENDING;
        this.result = null; //用来存储给then或者catch用
        //对应我们在promise时传入的函数:new Promise((resolve,reject) => {...})
        //需要的是,我们给他们绑定作用域,不然找不到status
        func(this.resolve.bind(this),this.reject.bind(this));
    }
    resolve(result){
        //需要保证resolve再函数循环执行队列的最后执行,所以再加一个计时器包裹
        setTimeout(()=>{
                    //只有在进行的时候才能执行resove,并对其改变状态
                    if(this.status === myPromise.PENDING){
                        this.status = myPromise.RESOLVED
                        this.result = result
                        //判断有无待执行的回调
                        this.resStack.forEach(callback=>{callback(result)})
                    }
        })
    }
    reject(result){
        //需要保证reject再函数循环执行队列的最后执行,所以再加一个计时器包裹
        setTimeout(()=>{
                    //只有在进行的时候才能执行reject,并对其改变状态
                    if(this.status === myPromise.PENDING){
                        this.status = myPromise.REJECTED
                        this.result = "error"
                        this.rejStack.forEach(callback=>{callback(result)})
                    }
        })
    }
    then(funcResolve,funcReject){
        //如果传入的参数不是函数的话我们需要先转化成函数
        funcReject =  typeof funcReject === 'function' ? funcReject : ()=>{}
        funcResolve =  typeof funcResolve === 'function' ? funcResolve : ()=>{}

        if(this.status === myPromise.PENDING){
            //保存回调到resolve中执行,让then等等resolve
            this.rejStack.push(funcReject)
            this.resStack.push(funcResolve)
        }else if(this.status === myPromise.RESOLVED){
            setTimeout(()=>funcResolve(this.result))//添加异步
        }
        else setTimeout(funcReject(this.result))
        //then返回还是promise
        return this
    }
    catch(func){
        if(this.status === myPromise.REJECTED){
            func(this.result)
        }
    }
}

let mp = new myPromise((resolve,reject)=>{
    setTimeout(()=>{resolve('111')})
    // resolve('111')
}).then((result)=>{
    console.log(result)
}).then((result)=>{
    console.log("ooooo")
})

猜你喜欢

转载自blog.csdn.net/qq_42533666/article/details/129220371