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)

 

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