promise 的实现

来实现一下Promise内部源码

//定义新的Promise类
class LxPromise{
            constructor(fn) {
                
                //将成功的事件函数集成在successList数组里
                this.successList  = [];
                //这里将全部的失败函数集成到failList里
                this.failList = []
                
                //pending,fullfilled,rejected
                
                this.state = "pending"

                //传入的函数对象,(异步操做的函数内容)
                //而且调用resolveFn()和rejectFn()方法
                //将resolveFn/rejectFn和传入的func绑定
                //resolve() => resolveFn()
                //reject() => rejectFn()
                fn(this.resolveFn.bind(this),this.rejectFn.bind(this))
            }
            
            //定义then方法,把传入的func压入list数组
            then(successFn,failFn){
                if(typeof successFn=='function'){
                    this.successList.push(successFn)
                }
                if(typeof failFn=='function'){
                    this.failList.push(failFn)
                }
            }
            catch(failFn){
                if(typeof failFn=='function'){
                    this.failList.push(failFn)
                }
            }

            //声明resolve实现函数
            resolveFn(res){
                this.state = "fullfilled"
                this.successList.forEach(function(item,index){
                    //将成功的事件循环调用
                    item(res)
                })
            }
            //声明reject实现函数
            rejectFn(res){
                this.state = 'rejected'
                //注册到的失败全部事件进行调用
                this.failList.forEach(function(item,index){
                    item(res)
                })
                
                throw Error(res);
            }
            
        }
//******************LxPromise()构造结束*****************

开始调用

//参数
        var fn = function(resolve,reject){
            setTimeout(function(){
                if(true){
                    //函数调用
                    resolve("老陈promise成功")
                }else{
                    //函数调用
                    reject("老陈promise失败")
                }
            },1000)
        }
        
        //建立实例对象
        var p1 = new LxPromise(fn);
        
        //函数声明,和函数的具体操做
        p1.then(function(res){
            document.body.style.background = "greenyellow"
            console.log("这是成功作的事情")
            console.log(res)
        })
        
        p1.catch(function(res){
            document.body.style.background = "pink"
            console.log("这是失败作的事情")
            console.log(res)
        })

ok~实现!可能还不是很完整,不过旨在学习认清promise的实现和运做过程。数组

相关文章
相关标签/搜索