实现 es6 Promise 原理

const PENDING='pending'
const RESOLVED='resolve'
const REJECTED='rejected'

function myPromise(fn){
    var that=this
    this.value=''
    this.resolveCallbacks=[]
    this.rejectCallbacks=[]
    this.state=PENDING

    function resolve(value){
        if(that.state==PENDING){
            that.value=value
            that.state=RESOLVED
            that.resolveCallbacks.map(cb=>{cb(that.value)})
        }    
    }

    function reject(value){
        if(that.state==PENDING){
            that.value=value
            that.state=REJECTED
            that.rejectCallbacks.map(cb=>{cb(that.value)})
        }
    }

    try{
        fn(resolve,reject)
    }catch(e){
        reject(e)
    }
}

myPromise.prototype.then=function(resolveFn,rejectFn){
    var that=this
    if(that.state==PENDING){
        that.resolveCallbacks.push(resolveFn)
        that.rejectCallbacks.push(rejectFn)
    }else if(that.state==RESOLVED){
        resolveFn(that.value)
        console.log('resolved')
    }else{
        rejectFn(that.value)
    }
}

var f=function(){
    return new myPromise((resolve,reject)=>{
        console.log("1")
    setTimeout(function(){
        console.log("2")
        resolve(3)
    },1000)
    })
}
f().then((res)=>{
    console.log(res)
})
发布了15 篇原创文章 · 获赞 21 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_41531446/article/details/88665740