栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

promise

promise

手写promise
class MyPromiseTest {

    static PENDING = '开始';
    static SUCCESS = '成功';
    static FAIL = '失败';
    
    constructor(func){
        this.status = MyPromiseTest.PENDING;
        this.result = null;
        this.resolveFun = [];
        this.rejectFun = [];
        try {
            func(this.resolve.bind(this),this.reject.bind(this))
        } catch (error) {
            this.reject(error)
        }
        
    }
    resolve(result){
        setTimeout(() => {
            if(this.status === MyPromiseTest.PENDING){
                this.status = MyPromiseTest.SUCCESS;
                this.result = result;
                this.resolveFun.forEach(item =>{
                    item(this.result);
                })
            }
        });
        
    }
    reject(result){
        setTimeout(() => {
            if(this.status === MyPromiseTest.PENDING){
                this.status = MyPromiseTest.FAIL;
                this.result = result;
                this.rejectFun.forEach(item =>{
                    item(this.result);
                })
            } 
        });

    then(OnResolve,OnReject){
        onResolve = typeof onResolve === 'function' ?  OnResolve : ()=>{};
        onReject = typeof onReject === 'function' ?  OnReject : ()=>{};

        if(this.status === MyPromiseTest.PENDING){
            this.resolveFun.push(OnResolve);
            this.rejectFun.push(OnReject);
        }
        if( this.status === MyPromiseTest.SUCCESS){
            setTimeout(() => {
                OnResolve(this.result) 
            });
            
        }
        if(this.status === MyPromiseTest.FAIL){
            setTimeout(() => {
                OnReject(this.result)
            });
            
        }
    }


}

console.log('1');
let pppp = new MyPromiseTest(function (resolve,reject) {
      console.log('2');
      setTimeout(() => {
        resolve('成果时....');
        console.log('4');
      }, 0);
     
     //只写一个reject的话
    //reject('不对');
     // throw new Error('错了');
})

// console.log(pppp);

pppp.then(
    function (d) { 
        console.log(d);
    },
    function(){

    }
)
console.log('3');
  • 遇到的问题
  •  1. 构造函数调用resolve方法,在构造的时候必须改变this指向
    

  •  2. 在then方法里变边,判断两个参数是否都有值.或者会报函数未定义错误
    

  •  3. 输出顺序问题,异步没有处理好
    

  •  4. 还是异步问题,若我们在创建实例的时候在配置里边添加延迟,延迟调用resolve方法,会出现调用then不输出结果的问题?
    

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/311245.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号