Promise核心原理实现一个简单版promise

创建 Promise类,加入三个最常用的回调函数,
class Promise {
    constructor(executor) {
        this.onResolved = []
        this.onRejected = []
        this.state = 'padding'
        try{
            executor(this.resolve.bind(this),this.reject.bind(this))
        }catch (e) {
           return e
        }
    }

    resolve(value) {
        if (this.state === 'padding') {
            this.state = 'resolved';
            process.nextTick(()=>{
                this.onResolved[0](value)
            })
        }
    }

    reject(value) {
        if (this.state === 'padding') {
            this.state = 'rejected';
            process.nextTick(()=>{
                this.onRejected[0](value)
            })
        }
    }

    then(resolve,rejected){
        this.onResolved.push(resolve)
        this.onRejected.push(rejected)
        // 此处应返回一个新的promise对象,满足调用结果传入下一个ten回调实现链式调用
        //因为立即resolev类方法没有做所以省略
    }
}

//===============================================

const pro=new Promise(function (resolve,rejected) {
    console.log("创建promise实例")
    setTimeout(()=>{
        rejected("错误回调啦!!!")
        resolve("成功回调啦!!!")
    },3000)
})

console.log("console打印")

pro.then((value)=>{
    console.log(value)
},(err)=>{
    console.log(err)
})
setTimeout(()=>{
    console.log("外层定时器")
},4000)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章