zoukankan      html  css  js  c++  java
  • 手写简易Promise

    记录贴

        // 手写promise
        function MyPromise(fn){
            let _this = this
            _this.status = "pending"
            _this.resolve_val = undefined
            _this.reject_val = undefined
            _this.resolveCb = []
            _this.rejectCb = []
            
            try{
                fn(resolve,reject)
            }catch(e){
                reject(e)
            }
            
            function resolve(value){
                if(_this.status === "pending"){
                    _this.status = "resolve"
                    _this.resolve_val = value
                    _this.resolveCb.map(cb=>cb(value))
                }
            }
            
            function reject(value){
                if(_this.status === "pending"){
                    _this.status = "reject"
                    _this.reject_val = value
                    _this.rejectCb.map(cb=>cb(value))
                }
            }
             
            
            MyPromise.prototype.then = function(success,fail){
                if(_this.status === "pending"){
                    _this.resolveCb.push(success)
                    _this.rejectCb.push(fail)
                }
                
                if(_this.status === "resolve"){
                    success(_this.resolve_val)
                }
                
                if(_this.status === "reject"){
                    fail(_this.resolve_val)
                }
                return this
            }
            
        }
    
        let p = new MyPromise((resolve,reject)=>{
            setTimeout(()=>{
                reject("你好")
            },2000)
        })
        p.then((e)=>{
            console.log(e)
        },(err)=>{
            console.log(err)
        })
  • 相关阅读:
    day74 作业
    day73 基表 表关联
    不知道第几次分享了
    day72 序列化家族
    day72 作业
    vscode
    vuex
    linux python3.7的安装和配置
    使用多线程分批发送短信代码,分割list
    docker 容器里使用crontab不生效
  • 原文地址:https://www.cnblogs.com/styleFeng/p/14193532.html
Copyright © 2011-2022 走看看