手寫實現簡易版Promise

//1.定義三種狀態
const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'
function MyPromisr(fn){
       //重命名this,防止接下來找不到正確的this
       const that = this
       that.state = PENDING //初始狀態爲等待
       that.value = null //value用於保存resolved或rejoiced傳入的值
       that.resolvedCallbacks = [] //成功請求後的回調數組
       //定義完成的回調函數
       function resolved(value) {
            // 只有在等待狀態才能夠改變狀態
            if (that.state === PENDING) {
                that.state = RESOLVED
                that.value = value
                that.resolvedCallbacks.map(cb => cb(that.value))
            }
        }
        //定義拒絕的回調函數
        function rejected(value) {
            // 只有在等待狀態才能夠改變狀態
            if (that.state === PENDING) {
                that.state = REJECTED
                that.value = value
                that.rejectedCallbacks.map(cb => cb(that.value))
            }
        }
        // 定義了兩種狀態的回調函數後,執行mypromise傳參的函數
        try {
            fn(resolved,rejected)
        } catch (e) {
            rejected(e)
        }
}
// 定義then
MyPromise.prototype.then = function(onFulfilled,onRejected){
    const that = this
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled :v => v
    onRejected = 
     typeof onRejected === 'function'
        ? onRejected
        : r => {
            throw r
        }
    if (that.state === PENDING) {
        that.resolvedCallbacks.push(onFulfilled)
        that.rejectedCallbacks.push(onRejected)
    }
    if (that.state === RESOLVED) {
        onFulfilled(that.value)
    }
    // console.log(that.state,'has change')
    if (that.state === REJECTED) {
        onRejected(that.value)
    }
}

//調用
new MyPromise((resolved,rejected) => {
    setTimeout(()=>{
        resolved(1)
        rejected(2)
    },0)
}).then(value=>{
    console.log(value)
},value=>{
    console.log(value)
})
相關文章
相關標籤/搜索