Promise學(xué)習(xí)筆記(知識點(diǎn) + 手寫Promise)

Promise標(biāo)準(zhǔn)了解一下

傳送門1?? ??Promises/A+規(guī)范

傳送門2?? ??阮一峰前輩ECMAScript 6入門——Promise對象

Promise重點(diǎn)難點(diǎn)

  • Promise的狀態(tài)不受外界影響,只由Promise內(nèi)的異步操作結(jié)果決定。

  • Promise的狀態(tài)一旦改變就不會再變。

    • pending ?? fulfilled
    • pending ?? rejected
  • Promise的構(gòu)造函數(shù)是同步的,then()方法中的函數(shù)是異步的。

  • then()方法或者catch()方法的參數(shù)期望是函數(shù),傳入非函數(shù)則會發(fā)生值穿透

  • Promise屬于microtask,同一次事件循環(huán)中,microtask永遠(yuǎn)在macrotask之前執(zhí)行。

手寫promise

  • 實(shí)現(xiàn)基本狀態(tài)(pending, fulfilled, rejected)
  • 實(shí)現(xiàn)then方法
    • 返回一個promise,實(shí)現(xiàn)鏈?zhǔn)秸{(diào)用
    • 實(shí)現(xiàn)狀態(tài)判斷
  • 實(shí)現(xiàn)resolve函數(shù)
    • 接受一個Promise作為參數(shù)時的情況,實(shí)現(xiàn)鏈?zhǔn)絇romise
  • 執(zhí)行回調(diào)函數(shù)時使用setTimeout,保證在注冊then方法后觸發(fā)
  • 實(shí)現(xiàn)Promise.all,Promise.race方法
(function (window) {
    var Promise = function (fn) {
        var value = null;
        var callbacks = [];
        var state = 'pending'; // pending, fulfilled, rejected

        var promise = this;

        // 注冊then事件,供resolve后調(diào)用
        promise.then = function (onFulfilled, onRejected) {
            // 返回promise實(shí)現(xiàn)鏈?zhǔn)絧romise調(diào)用
            return new Promise(function (resolve, reject) {
                handle({
                    onFulfilled: onFulfilled || null,
                    onRejected: onRejected || null,
                    resolve: resolve,
                    reject: reject
                })
            })
        }

        promise.catch = function(onRejected) {
            return promise.then(undefined, onRejected)
        }
        
        function handle (callback) {
            // 狀態(tài)變化前,事件推進(jìn)隊(duì)列里;狀態(tài)一旦變化后不再變動,直接執(zhí)行結(jié)果
            if (state === 'pending') {
                callbacks.push(callback);
            } else {
                var cb = state === 'fulfilled' ? callback.onFulfilled : callback.onRejected
                // then方法沒有傳遞任何參數(shù)的情況下,返回結(jié)果值
                if (!cb) {
                    cb = state === 'fulfilled' ? callback.resolve : callback.reject;
                    cb(value)
                } else {
                    try {
                        var ret = cb(value);
                        callback.resolve(ret);
                    } catch (e) {
                        callback.reject(e)
                    }  
                }
            }
        }

        function resolve(newValue) {
            // 狀態(tài)一旦改變便不再改變
            if (state !== 'pending') return
            // 假如resolve了一個promise的話(鏈?zhǔn)絧romise)
            if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
                var then = newValue.then;
                if (typeof then === 'function') {
                    // 調(diào)用第二個promise中的then,遞歸直到不是一個promise值為止
                    then.call(newValue, resolve, reject);
                    return
                }
            }

            value = newValue;
            state = 'fulfilled';
            
            execute()
        }

        function reject(reason) {
            // 狀態(tài)一旦改變便不再改變
            if (state !== 'pending') return
            state = 'rejected'
            value = reason

            execute()
        }

        function execute() {
            // 使用setTimeOut保證resolve一定在then事件注冊后執(zhí)行
            setTimeout(() => {
                callbacks.forEach(function (callback) {
                    handle(callback);
                })
            }, 0);
        }

        fn(resolve, reject);
    }

    Promise.all = function (promises) {
        if (!Array.isArray(promises)) {
            throw new TypeError('請傳入promise數(shù)組')
        }

        return new Promise(function (resolve, reject) {
            var result = [];
            var count = promises.length

            function reslover (index) {
                return function(value) {
                    resloveAll(index, value)
                }
            }
    
            function rejecter (reason) {
                reject(reason)
            }
    
            function resloveAll (index, value) {
                result[index] = value
                // 等待全部promise執(zhí)行完才執(zhí)行resolve一個數(shù)組
                if (--count === 0) {
                    resolve(result)
                }
            }

            promises.forEach(function (promise, index) {
                promise.then(reslover(index), rejecter)
            })
        })
    }

    Promise.race = function (promises) {
        if (!Array.isArray(promises)) {
            throw new TypeError('請傳入promise數(shù)組')
        }

        return new Promise(function (resolve, reject) {
            function reslover (value) {
                resolve(value)
            }
    
            function rejecter (reason) {
                reject(reason)
            }
            promises.forEach(function (promise, index) {
                promise.then(reslover, rejecter)
            })
        })
    }

    window.Promise = Promise

})(window)

/******************************************實(shí)例 */
function test(i) {
    return new Promise(function (resolve) {
        setTimeout(() => {
        resolve(i); 
        }, 1000);
    })
}

function test2(i) {
    return new Promise(function (resolve, reject) {
        setTimeout(() => {
            if (i % 2) {
            resolve(i);  
            } else {
            reject(i); 
            }
        }, 2000);
    })
}

// 鏈?zhǔn)絇romise
test(1).then(test2).then(function (something) {
    console.log('case1: success!' + something);
}).catch(function (something) {
    console.log('case1: failed!' + something);
})

// Promise.all
Promise.all([test(2), test2(4)]).then(function (something) {
    console.log('case2: success!' + something);
}).catch(function (something) {
    console.log('case2: failed!' + something)
})

// Promise.race
Promise.race([test(3), test2(5)]).then(function (something) {
    console.log('case3: success!' + something);
}).catch(function (something) {
    console.log('case3: failed!' + something)
})

// 多次改變狀態(tài),只有第一次生效
function test3 () {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('success1')
            reject('error')
            resolve('success2')
        },0)
    })
}

test3().then((res) => {
    console.log('then: ', res)
})

// 一旦改變狀態(tài)后,多次調(diào)用then()方法也只會馬上得到Promise返回的值,Promise構(gòu)造函數(shù)不會多次執(zhí)行
function test4 () {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
        resolve('success')
        }, 1000)
    })
}
  
const start = Date.now()
test4().then((res) => {
    console.log(res, Date.now() - start)
})
test4().then((res) => {
    console.log(res, Date.now() - start)
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

  • Promise含義 Promise是異步編程的一種解決方案,比傳統(tǒng)的解決方案——回調(diào)函數(shù)和事件——更強(qiáng)大。所謂Pr...
    oWSQo閱讀 1,141評論 0 4
  • title: promise總結(jié) 總結(jié)在前 前言 下文類似 Promise#then、Promise#resolv...
    JyLie閱讀 12,428評論 1 21
  • 目錄:Promise 的含義基本用法Promise.prototype.then()Promise.prototy...
    BluesCurry閱讀 1,575評論 0 8
  • 00、前言Promise 是異步編程的一種解決方案,比傳統(tǒng)的解決方案——回調(diào)函數(shù)和事件——更合理和更強(qiáng)大。它由社區(qū)...
    夜幕小草閱讀 2,230評論 0 12
  • 一個明媚的早晨,我看了看鐘,突然發(fā)現(xiàn)鬧鐘旁有一個黑黑的小圓點(diǎn)。我仔細(xì)一看原來是蜘蛛在織網(wǎng)。我很想看看蜘蛛是怎樣織網(wǎng)...
    鄒秉軒小可愛閱讀 284評論 1 3

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