手写Promise

promise的原理

  • 回调地狱:当想要异步任务按顺序执行时,用回调函数套回调函数实现,这种情况就叫回调地狱。
  • promise就是用来解决回调地狱问题的
  • promise在A+规范里面就是一个带.then()方法的对象或函数
  • promise在ES6里面,是一个构造函数,通过这个构造函数创建的实例满足了promiseA+规范
  • promise有三种状态:Pending(进行中)、Fulfilled(已成功)、Rejected(已失败)。一个 Promise 对象只能从 Pending 状态转换到 Fulfilled 或 Rejected 状态,并且状态转换是不可逆的。
  • 在函数内返回一个promise对象,可以接着.then(),不需要套娃操作。
  • .then一大堆,可以用建立在 Promise 之上的语法糖async/await,把本来是异步的代码,看上去是同步。

手写Promise

class MyPromise{
    //有三种状态
    static PENDING='待定'; FULFILLED='成功';REJECTED='拒绝';
    constructor(func){
        //设置默认状态为pending
        this.status=MyPromise.PENDING;
        this.result=null;
        this.resolveCallbacks=[];
        this.rejectCallbacks=[];
        try{
            func(this.resolve.bind(this),this.reject.bind(this));//加上bind解决this指向问题
        }catch(error){
            this.reject(error);
        }
        
    }
    resolve(result){
        setTimeout(()=>{
            if(this.status===MyPromise.PENDING){
                this.status=MyPromise.FULFILLED;
                this.result=result;
                this.resolveCallbacks.forEach(callback=>{
                    callback(result)
                });
            }
        })
    }
    reject(result){
        setTimeout(()=>{
            if(this.status===MyPromise.PENDING){
                this.status=MyPromise.REJECTED;
                this.result=result;
                this.rejectCallbacks.forEach(callback=>{
                    callback(result)
                });
            }
        })
    }
    //只会执行成功或者失败
    then(onFULFILLED,onREJECTED){
        //返回promise对象,保证then的链式
        return new MyPromise(()=>{
            //确保传入参数
        onFULFILLED=typeof onFULFILLED === 'function'?onFULFILLED:()=>{};
        onREJECTED=typeof onREJECTED === 'function'?onREJECTED:()=>{};
        if (this.status===MyPromise.PENDING){
            this.resolveCallbacks.push(onFULFILLED);
            this.resolveCallbacks.push(onREJECTED);   
        }
        if (this.status===MyPromise.FULFILLED){
            setTimeout(()=>{
                onFULFILLED(this.result);
            });
        }
        if (this.status===MyPromise.REJECTED){
            setTimeout(()=>{
                onREJECTED(this.result);
            })
        }
        })
    }
}
posted @ 2024-05-26 15:19  Frommoon  阅读(1)  评论(0编辑  收藏  举报