實現(xiàn)簡單的promise

實現(xiàn)promise必須符合promise A plus的規(guī)范 官方網(wǎng)址 https://promisesaplus.com/

  • promise 有三種狀態(tài):等待態(tài),成功態(tài),失敗態(tài)。狀態(tài)改變后不可逆。
  • promise.then 有兩個參數(shù) 第一個參數(shù)是成功的回調(diào),第二個參數(shù)是失敗的回調(diào)
const RESOLVE = "reslove"
const REJECT = "reject"
const PENDING = "pending"

class Promise{
    constructor(executor){
        this.status = PENDING
        this.value = undefined
        this.reason = undefined
        this.onResolvedCallbacks = []
        this.onRejectedCallbacks = []

        let reslove = (value)=>{
            this.status = RESOLVE
            this.value = value
            this.onResolvedCallbacks.forEach(item=>item())
        }

        let reject = (reason)=>{
            this.status = REJECT
            this.reason = reason
            this.onRejectedCallbacks.forEach(item=>item())
        }

        try{
            executor(reslove,reject)
        }catch(e){
            reject(e)
        }
    }

    then(onFulfilled, onRejected){
        if(this.status === RESOLVE){
            onFulfilled(this.value)
        }
        if(this.status === REJECT){
            onRejected(this.reason)
        }

        if(this.status === PENDING){
            this.onResolvedCallbacks.push(()=>{
                onFulfilled(this.value)
            })
            this.onRejectedCallbacks.push(()=>{
                onRejected(this.reason)
            })
        }
    }
}

let promiseA = new Promise((resolve, reject)=>{
    setTimeout(()=>{
        resolve("aaa")
    },2000)
})
promiseA.then((res)=>{
    console.log("success1",res)
})

promiseA.then((res)=>{
    console.log("success2",res)
})

let promiseB = new Promise((resolve, reject)=>{
    console.log("1")
    reject("aaa")
})
console.log(2)
promiseB.then((res)=>{
    console.log("success",res)
},(err)=>{
    console.log("err",err)
})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容