手寫(xiě)Promise的實(shí)現(xiàn)和心得

//This is javascript
class myPromise{
    constructor(executor){
        this.state = 'pending';
        this.value = null;
        this.reason = null;
        this.onFullfilledCallbacks = [];
        this.onRejectedCallbacks = [];

        let resolve = (value) => {
            if (this.state === 'pending') {
                this.value = value;
                this.state = 'fullfilled';
                this.onFullfilledCallbacks.forEach(fn => fn());
            }
        }

        let reject = (reason) => {
            if (this.state === 'pending') {
                this.state = 'rejected';
                this.reason = reason;
                this.onRejectedCallbacks.forEach(fn => fn());
            }
        }

        try{
            executor(resolve,reject)
        }catch(e) {
            reject(e);
        }
    }

    then(onFullfilled,onRejected) {
        // then函數(shù)的作用有兩個(gè)
        // 1、返回一個(gè)promise,后面還可以繼續(xù).then,把回調(diào)記錄在本身promise實(shí)例上面
        // 2、在promise的executor里面把訂閱函數(shù)記錄在callbacks當(dāng)中,要么同步直接執(zhí)行,要么異步由resolve來(lái)觸發(fā)
        onFullfilled = typeof onFullfilled === 'function'?onFullfilled:value => value;
        onRejected = typeof onRejected === 'function'?onRejected:err => {throw err};
        let promise2 = new myPromise((resolve,reject) => {
            if (this.state === 'fullfilled') {
                setTimeout(() => {
                    try{
                        let x = onFullfilled(this.value);
                        // 這里是最核心的地方,需要解析then的fullfill函數(shù)的返回值,當(dāng)前這個(gè)promise需要觸發(fā)自己的resolve函數(shù),才能讓后面的then邏輯執(zhí)行
                        // 如果是普通值,那么觸發(fā)這里的resolve后面的就可以執(zhí)行了,如果返回的本身也是一個(gè)promise,那就在當(dāng)前的promise后面加一個(gè)then執(zhí)行完之后來(lái)resolve當(dāng)前的這個(gè)promise
                        this.resolvePromise(promise2,x,resolve,reject);
                    }catch(e) {
                        reject(e);
                    }
                },0);
            }

            if (this.state === 'rejected') {
                setTimeout(() => {
                    try{
                        let x = onRejected(this.reason);
                        this.resolvePromise(promise2,x,resolve,reject);
                    }catch(e) {
                        reject(e);
                    }
                },0);
            }

            if (this.state === 'pending') {
                this.onFullfilledCallbacks.push(() => {
                    setTimeout(() => {
                        try{
                            let x = onFullfilled(this.value);
                            this.resolvePromise(promise2,x,resolve,reject);
                        }catch(e) {
                            reject(e);
                        }
                    },0);
                })

                this.onRejectedCallbacks.push(() => {
                    setTimeout(() => {
                        try{
                            let x = onRejected(this.reason);
                            this.resolvePromise(promise2,x,resolve,reject);
                        }catch(e) {
                            reject(e);
                        }
                    },0);
                })
            }
        })
        return promise2;
    }

    resolvePromise(promise2,x,resolve,reject) {
        if (promise2 === x) {
            reject(new TypeError('circular reference'));
        }

        let called;
        if (x !== null && (typeof x === 'function' || typeof x === 'object')) {
            try{
                let then = x.then;
                if (typeof then === 'function') {
                    then.call(x,y => {
                        if (called) return;
                        called = true;
                        this.resolvePromise(promise2,y,resolve,reject);
                    },err => {
                        if (called) return;
                        called = true;
                        reject(err);
                    })
                }else {
                    if (called) return;
                    called = true;
                    resolve(x);
                }
            }catch(e) {
                if (called) return;
                called = true;
                reject(e);
            }
        }else {
            if (called) return;
            called = true;
            resolve(x);
        }
    }


    static resolve(value) {
        if (value instanceof myPromise) {
            return value;
        }

        return new myPromise((resolve,reject) => {
            resolve(value);
        })
    }

    static reject(value) {
        if (value instanceof myPromise) {
            return value;
        }

        return new myPromise((resolve,reject) => {
            reject(value);
        })
    }

    static all(promiseArray) {
        if (!Array.isArray(promiseArray)) {
            throw new TypeError('must be an array');
        }
        let result = [],
        i = 0;
        return new myPromise((resolve,reject) => {
            if (promiseArray.length === 0) {
                resolve(result);
            }else {
                promiseArray.forEach((pro,index) => {
                    if (pro instanceof myPromise) {
                        pro.then(value => {
                            result[index] = value;
                            i++;
                            if (i === promiseArray.length) {
                                resolve(result);
                            }
                        },err => {
                            reject(err);
                        })
                    }else {
                        result[index] = pro;
                        i++;
                        if (i === promiseArray.length) {
                            resolve(result);
                        }
                    }
                })
            }
        })
    }

    static race(promiseArray) {
        if (!Array.isArray(promiseArray)) {
            throw new TypeError('must be an array');
        }

        let flag = true;

        return new myPromise((resolve,reject) => {
            promiseArray.forEach(pro => {
                if (pro instanceof myPromise) {
                    pro.then(res => {
                        if (flag) {
                            flag = false;
                            resolve(res);
                        }
                    },err => {
                        if (flag) {
                            flag = false;
                            reject(err);
                        }
                    })
                }else {
                    if (flag) {
                        flag = false;
                        resolve(pro)
                    }
                }
            })
        })
    }
}

try{
    module.exports = myPromise;
}catch(e) {}

實(shí)現(xiàn)的邏輯和說(shuō)明

上述代碼基本上實(shí)現(xiàn)了所有的Promise/A+規(guī)范,實(shí)現(xiàn)了promise的靜態(tài)resolve和reject方法,也實(shí)現(xiàn)了all和race方法。
1.onFullfilled那里,給了一個(gè)包裝,如果不是方法的話,就稱為一個(gè)參數(shù)為value,return value的方法,實(shí)現(xiàn)了值穿透
2.then里面的方法都是異步的,都要加settimeout
3.resolvePromise放在了對(duì)象里頭,作為原型方法,要控制x的狀態(tài)不可改動(dòng),所以外層加入called,只要執(zhí)行了該promise的resolve或者reject,就不能夠再改動(dòng)
4.all方法就是把所有promise對(duì)象執(zhí)行的結(jié)果,給result,然后外層的promise去resolve那個(gè)result即可
5.race方法,就是全部promise都執(zhí)行then方法,then方法執(zhí)行的時(shí)候,成功回調(diào)或者失敗回調(diào)的時(shí)候會(huì)改掉flag,所以只有最先執(zhí)行成功或者失敗回調(diào)的那個(gè)promise的值會(huì)給外層的promise去resolve
6.resolvePromise方法,可以想象為外層的promise對(duì)象,用自己的resolve和reject一直在找返回值,如果返回值還是promise就繼續(xù)往下遞歸,直到找到那個(gè)普通值,然后給resolve掉,不達(dá)目的不罷休

總結(jié)而言,實(shí)現(xiàn)promise還是有一點(diǎn)復(fù)雜的,其中涉及到this指向的細(xì)節(jié)解析then內(nèi)部返回值的問(wèn)題,代碼大概200行,沒(méi)有寫(xiě)注釋,留此博客歡迎交流

這里記錄一個(gè)promise的打印順序,把前面提到的東西都加進(jìn)去

new Promise((resolve, reject) => {
    console.log(1);
    setTimeout(() => {
        console.log(2);
        resolve(1)
    }, 3000)
}).then(res => {
    // 成功的回調(diào)
    console.log(3);
    return new Promise((resolve1) => {
        console.log(4);
        setTimeout(() => {
            console.log(5);
            resolve1()
        }, 3000)
    }).then(() => {
        // 其實(shí)這里的then會(huì)全部跑完才會(huì)resolve外面的
        console.log(6)
    })
}).then(() => {
    console.log(7)
})

上述的打印結(jié)果是1234567,如果then里面返回promise的話,會(huì)等promise所有都結(jié)束了之后才會(huì)resolve,這就是resolvePromise做的事情,因?yàn)樗谧詈笠粋€(gè)promise后面加了一個(gè)then

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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