promise的实现

143 阅读1分钟

闲来无事 仔细学习一下pormise, 之前用的挺顺,以为自己是会的,一般我就这样用

是没毛病,用起来确实ok,但是想研究的更深一点promise的原理,也因为看见了这个玩意

    Promise.resolve('go').then().then((res)=>{
        console.log(res)
    })
    // ??? 看见这个玩意脑袋都大了,几个意思 不按套路出牌  res是go
    还有这个
    Promise.resolve('go').then(()=>{return 'nogo'}).then((res)=>{
        console.log(res)
    })
    //res 是 nogo 
    Promise.resolve('go').then(()=>{}).then((res)=>{
        console.log(res)
    })
    //res 是undefined

看见这些刁钻的东西 快被玩吐了,不知道在干什么 下决心研究了一下 发现.then()后 会返回原来的promise对象 然后看过教程之后写一个最简单最low的promise出来

    function myPromise( executor){
        let callback,//这个就是拿来装.then()里面的函数参数
        that=this
        //resolve函数就是把promise从pending变为resovle的函数  参数value就是到时候比如请求完毕之后的结果丢进resolve里面去做参数
        function resolve( value){   
            setTimeout(()=>{ //定时器做异步 要保证resolve在.then执行之后 
                callback&&callbakc(value)
            })
        }
        that.then=function(fn){
            callback=fn //在.then里面会传一个函数  拿到promise里面执行的结果作为参数进行执行
            
            return that  //把promise对象return 可以一直.then().then()下去
        }
        executor(resolve)
        
        //
    }

这样一个很简单的很low的promise就完成了 虽然完全没有处理reject的能力, 不过问题不大,以后再慢慢完善.其实这个函数的原理还是跟回调差不多 用定时器强行做异步,使.then后面的函数拿到resolve里面去执行