實現(xiàn)一個基本的Promise

// 定義Promise的三種狀態(tài)常量
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

function MyPromise(executor) {
    this.status = PENDING   // 默認(rèn)的時候的PENDING
    this.value = null    // 成功時候的值
    this.reason = null    // 失敗時候的值
    this.onResolvedCallbacks = []   // 成功時候的回調(diào)
    this.onRejectedCallbacks = []   // 失敗時候的回調(diào)

    let _this = this;
    // 內(nèi)部的resolve方法
    function resolve(value) {
        if (_this.status === PENDING) {
            // 改變Promise狀態(tài),設(shè)置值
            _this.value = value
            _this.status = FULFILLED
            // 若是異步的情況下,需要調(diào)用它原來then中傳入的函數(shù)
            _this.onResolvedCallbacks.forEach(fn => fn())
        }
    }

    // 內(nèi)部的reject方法
    function reject(reason) {
        // 改變Promise狀態(tài),設(shè)置值
        if (_this.status === PENDING) {
            _this.reason = reason
            _this.status = REJECTED
            // 若是異步的情況下,需要調(diào)用它原來then中傳入的函數(shù)
            _this.onRejectedCallbacks.forEach(fn => fn())
        }
    }

    try {
        // 執(zhí)行Promise內(nèi)的代碼
        executor(resolve, reject)
    } catch (error) {
        // 執(zhí)行中有錯誤的話捕捉
        reject(error)
    }
}

function resolvePromise(promise2, x, resolve, reject) {
    // 如果promise2, x和相等,那么就循環(huán)引用了,表示兩個永遠(yuǎn)等不到結(jié)果(resolve/reject)
    if (promise2 === x) {
        reject(new Error('循環(huán)引用'))
        return;
    }
    let called = false; // 避免多次調(diào)用
    if (typeof x != null && (typeof x === 'function' || typeof x === 'object')) {
        try {
            let then = x.then;
            if (typeof then === 'function') {   // 如果x.then是一個函數(shù)(有可能包含在對象屬性中不是函數(shù)),調(diào)用該then方法,
                then.call(x, y => {
                    // y有可能也是Promise,所以還需要繼續(xù)resolvePromise
                    if(called) return;
                    called = true;
                    resolvePromise(promise2, y, resolve, reject);
                }, reason => {
                    reject(reason);
                })
            } else {
                //x是一個對象,也可以直接resolve
                if(called) return;
                called = true;
                resolve(x)
            }
        } catch (error) {
            if(called) return;
            called = true;
            reject(error)
        }
    } else {
        // 如果x是普通值的情況可以直接resolve
        resolve(x)
    }
}

MyPromise.prototype.then = function (onFulfilled, onRejected) {
    // 如果傳入的onFulfilled, onRejected不是一個函數(shù)的話,那么要轉(zhuǎn)換成函數(shù),用于在鏈?zhǔn)秸{(diào)用時能獲得上一個相同的值
    onFulfilled = onFulfilled === 'function' ? onFulfilled : value => value
    onRejected = onRejected === 'function' ? onRejected : reason => reason
    let _this = this;
    // PromiseA+規(guī)范中寫明: then方法必須返回一個新的Promise
    let promise2 = new MyPromise(function (resolve, reject) {
        if (_this.status === PENDING) {
            // 如果調(diào)用then方法的時候,此時Promise的狀態(tài)還是PENDING的話,那么把then中的兩個回調(diào)函數(shù)傳到內(nèi)部的數(shù)組中存放
            // ,等到調(diào)用resolve/reject方法的時候再執(zhí)行里面的代碼
            _this.onResolvedCallbacks.push(function () {
                let x = onFulfilled(_this.value)
                resolvePromise(promise2, x, resolve, reject)
            })
            _this.onRejectedCallbacks.push(function () {
                let x = onRejected(_this.reason)
                resolvePromise(promise2, x, resolve, reject)
            })
        } else if (_this.status === FULFILLED) {
            // 此時Promise的狀態(tài)是FULFILLED的話,那么直接調(diào)用傳入的onFulfilled方法就行
            let x = onFulfilled(_this.value)
            // 1. 由于then中需要返回一個Promise,那么這個Promise要怎樣才能被resolve或reject呢?
            // 2. 如果調(diào)用onFulfilled的返回值x也是一個Promise怎么辦
            // 通過實現(xiàn)一個resolvePromise的方法來解決他們之間的resolve或者reject的問題。
            resolvePromise(promise2, x, resolve, reject)
        } else if (_this.status === REJECTED) {
            // 此時Promise的狀態(tài)是REJECTED的話,那么直接調(diào)用傳入的onRejected方法就行
            let x = onRejected(_this.reason)
            // 1. 由于then中需要返回一個Promise,那么這個Promise要怎樣才能被resolve或reject呢?
            // 2. 如果調(diào)用onRejected的返回值x也是一個Promise怎么辦
            // 通過實現(xiàn)一個resolvePromise的方法來解決他們之間的resolve或者reject的問題。
            resolvePromise(promise2, x, resolve, reject)
        }
    })
    return promise2;
}

module.exports = MyPromise

?著作權(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ù)。

相關(guān)閱讀更多精彩內(nèi)容

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