Promise原理講解 && 實現一個Promise對象 (遵循Promise/A+規範)

提示:本篇文章的Promise代碼實現部分講解不夠由淺入深, 推薦你們看我另外一篇更細緻的講解Promise實現原理的分析文章:《從零一步一步實現一個完整版的Promise》javascript

1.什麼是Promise?

Promise是JS異步編程中的重要概念,異步抽象處理對象,是目前比較流行Javascript異步編程解決方案之一html

2.對於幾種常見異步編程方案

這裏就拿回調函數說說

(1) 對於回調函數 咱們用Jquery的ajax獲取數據時 都是以回調函數方式獲取的數據前端

$.get(url, (data) => {
    console.log(data)
)
複製代碼

(2) 若是說 當咱們須要發送多個異步請求 而且每一個請求之間須要相互依賴 那這時 咱們只能 以嵌套方式來解決 造成 "回調地獄"vue

$.get(url, data1 => {
    console.log(data1)
    $.get(data1.url, data2 => {
        console.log(data1)
    })
})
複製代碼

這樣一來,在處理越多的異步邏輯時,就須要越深的回調嵌套,這種編碼模式的問題主要有如下幾個:java

  • 代碼邏輯書寫順序與執行順序不一致,不利於閱讀與維護。
  • 異步操做的順序變動時,須要大規模的代碼重構。
  • 回調函數基本都是匿名函數,bug 追蹤困難。
  • 回調函數是被第三方庫代碼(如上例中的 ajax )而非本身的業務代碼所調用的,形成了 IoC 控制反轉。

Promise 處理多個相互關聯的異步請求

(1) 而咱們Promise 能夠更直觀的方式 來解決 "回調地獄"node

const request = url => { 
    return new Promise((resolve, reject) => {
        $.get(url, data => {
            resolve(data)
        });
    })
};

// 請求data1
request(url).then(data1 => {
    return request(data1.url);   
}).then(data2 => {
    return request(data2.url);
}).then(data3 => {
    console.log(data3);
}).catch(err => throw new Error(err));
複製代碼

(2) 相信你們在 vue/react 都是用axios fetch 請求數據 也都支持 Promise APIreact

import axios from 'axios';
axios.get(url).then(data => {
   console.log(data)
})
複製代碼

Axios 是一個基於 promise 的 HTTP 庫,能夠用在瀏覽器和 node.js 中。jquery

3.Promise使用

Promise 是一個構造函數, new Promise 返回一個 promise對象 接收一個excutor執行函數做爲參數, excutor有兩個函數類型形參resolve reject

const promise = new Promise((resolve, reject) => {
       // 異步處理
       // 處理結束後、調用resolve 或 reject
});

複製代碼

promise至關於一個狀態機

promise的三種狀態ios

  • pending
  • fulfilled
  • rejected

(1) promise 對象初始化狀態爲 pendinggit

(2) 當調用resolve(成功),會由pending => fulfilled

(3) 當調用reject(失敗),會由pending => rejected

注意promsie狀態 只能由 pending => fulfilled/rejected, 一旦修改就不能再變

promise對象方法

(1) then方法註冊 當resolve(成功)/reject(失敗)的回調函數

// onFulfilled 是用來接收promise成功的值
// onRejected 是用來接收promise失敗的緣由
promise.then(onFulfilled, onRejected);
複製代碼

注意:then方法是異步執行的

(2) resolve(成功) onFulfilled會被調用

const promise = new Promise((resolve, reject) => {
   resolve('fulfilled'); // 狀態由 pending => fulfilled
});
promise.then(result => { // onFulfilled
    console.log(result); // 'fulfilled' 
}, reason => { // onRejected 不會被調用
    
})
複製代碼

(3) reject(失敗) onRejected會被調用

const promise = new Promise((resolve, reject) => {
   reject('rejected'); // 狀態由 pending => rejected
});
promise.then(result => { // onFulfilled 不會被調用
  
}, reason => { // onRejected 
    console.log(reason); // 'rejected'
})
複製代碼

(4) promise.catch

在鏈式寫法中能夠捕獲前面then中發送的異常,

promise.catch(onRejected)
至關於
promise.then(null, onRrejected);

// 注意
// onRejected 不能捕獲當前onFulfilled中的異常
promise.then(onFulfilled, onRrejected); 

// 能夠寫成:
promise.then(onFulfilled)
       .catch(onRrejected); 
複製代碼

promise chain

promise.then方法每次調用 都返回一個新的promise對象 因此能夠鏈式寫法

function taskA() {
    console.log("Task A");
}
function taskB() {
    console.log("Task B");
}
function onRejected(error) {
    console.log("Catch Error: A or B", error);
}

var promise = Promise.resolve();
promise
    .then(taskA)
    .then(taskB)
    .catch(onRejected) // 捕獲前面then方法中的異常
複製代碼

Promise的靜態方法

(1) Promise.resolve 返回一個fulfilled狀態的promise對象

Promise.resolve('hello').then(function(value){
    console.log(value);
});

Promise.resolve('hello');
// 至關於
const promise = new Promise(resolve => {
   resolve('hello');
});
複製代碼

(2) Promise.reject 返回一個rejected狀態的promise對象

Promise.reject(24);
new Promise((resolve, reject) => {
   reject(24);
});
複製代碼

(3) Promise.all 接收一個promise對象數組爲參數

只有所有爲resolve纔會調用 一般會用來處理 多個並行異步操做

const p1 = new Promise((resolve, reject) => {
    resolve(1);
});

const p2 = new Promise((resolve, reject) => {
    resolve(2);
});

const p3 = new Promise((resolve, reject) => {
    resolve(3);
});

Promise.all([p1, p2, p3]).then(data => { 
    console.log(data); // [1, 2, 3] 結果順序和promise實例數組順序是一致的
}, err => {
    console.log(err);
});
複製代碼

(4) Promise.race 接收一個promise對象數組爲參數

Promise.race 只要有一個promise對象進入 FulFilled 或者 Rejected 狀態的話,就會繼續進行後面的處理。

function timerPromisefy(delay) {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve(delay);
        }, delay);
    });
}
var startDate = Date.now();

Promise.race([
    timerPromisefy(10),
    timerPromisefy(20),
    timerPromisefy(30)
]).then(function (values) {
    console.log(values); // 10
});
複製代碼

4.Promise 代碼實現

/** * Promise 實現 遵循promise/A+規範 * Promise/A+規範譯文: * https://malcolmyu.github.io/2015/06/12/Promises-A-Plus/#note-4 */

// promise 三個狀態
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";

function Promise(excutor) {
    let that = this; // 緩存當前promise實例對象
    that.status = PENDING; // 初始狀態
    that.value = undefined; // fulfilled狀態時 返回的信息
    that.reason = undefined; // rejected狀態時 拒絕的緣由
    that.onFulfilledCallbacks = []; // 存儲fulfilled狀態對應的onFulfilled函數
    that.onRejectedCallbacks = []; // 存儲rejected狀態對應的onRejected函數

    function resolve(value) { // value成功態時接收的終值
        if(value instanceof Promise) {
            return value.then(resolve, reject);
        }

        // 爲何resolve 加setTimeout?
        // 2.2.4規範 onFulfilled 和 onRejected 只容許在 execution context 棧僅包含平臺代碼時運行.
        // 注1 這裏的平臺代碼指的是引擎、環境以及 promise 的實施代碼。實踐中要確保 onFulfilled 和 onRejected 方法異步執行,且應該在 then 方法被調用的那一輪事件循環以後的新執行棧中執行。

        setTimeout(() => {
            // 調用resolve 回調對應onFulfilled函數
            if (that.status === PENDING) {
                // 只能由pending狀態 => fulfilled狀態 (避免調用屢次resolve reject)
                that.status = FULFILLED;
                that.value = value;
                that.onFulfilledCallbacks.forEach(cb => cb(that.value));
            }
        });
    }

    function reject(reason) { // reason失敗態時接收的拒因
        setTimeout(() => {
            // 調用reject 回調對應onRejected函數
            if (that.status === PENDING) {
                // 只能由pending狀態 => rejected狀態 (避免調用屢次resolve reject)
                that.status = REJECTED;
                that.reason = reason;
                that.onRejectedCallbacks.forEach(cb => cb(that.reason));
            }
        });
    }

    // 捕獲在excutor執行器中拋出的異常
    // new Promise((resolve, reject) => {
    // throw new Error('error in excutor')
    // })
    try {
        excutor(resolve, reject);
    } catch (e) {
        reject(e);
    }
}

/** * resolve中的值幾種狀況: * 1.普通值 * 2.promise對象 * 3.thenable對象/函數 */

/** * 對resolve 進行改造加強 針對resolve中不一樣值狀況 進行處理 * @param {promise} promise2 promise1.then方法返回的新的promise對象 * @param {[type]} x promise1中onFulfilled的返回值 * @param {[type]} resolve promise2的resolve方法 * @param {[type]} reject promise2的reject方法 */
function resolvePromise(promise2, x, resolve, reject) {
    if (promise2 === x) {  // 若是從onFulfilled中返回的x 就是promise2 就會致使循環引用報錯
        return reject(new TypeError('循環引用'));
    }

    let called = false; // 避免屢次調用
    // 若是x是一個promise對象 (該判斷和下面 判斷是否是thenable對象重複 因此無關緊要)
    if (x instanceof Promise) { // 得到它的終值 繼續resolve
        if (x.status === PENDING) { // 若是爲等待態需等待直至 x 被執行或拒絕 並解析y值
            x.then(y => {
                resolvePromise(promise2, y, resolve, reject);
            }, reason => {
                reject(reason);
            });
        } else { // 若是 x 已經處於執行態/拒絕態(值已經被解析爲普通值),用相同的值執行傳遞下去 promise
            x.then(resolve, reject);
        }
        // 若是 x 爲對象或者函數
    } else if (x != null && ((typeof x === 'object') || (typeof x === 'function'))) {
        try { // 是不是thenable對象(具備then方法的對象/函數)
            let then = x.then;
            if (typeof then === 'function') {
                then.call(x, y => {
                    if(called) return;
                    called = true;
                    resolvePromise(promise2, y, resolve, reject);
                }, reason => {
                    if(called) return;
                    called = true;
                    reject(reason);
                })
            } else { // 說明是一個普通對象/函數
                resolve(x);
            }
        } catch(e) {
            if(called) return;
            called = true;
            reject(e);
        }
    } else {
        resolve(x);
    }
}

/** * [註冊fulfilled狀態/rejected狀態對應的回調函數] * @param {function} onFulfilled fulfilled狀態時 執行的函數 * @param {function} onRejected rejected狀態時 執行的函數 * @return {function} newPromsie 返回一個新的promise對象 */
Promise.prototype.then = function(onFulfilled, onRejected) {
    const that = this;
    let newPromise;
    // 處理參數默認值 保證參數後續可以繼續執行
    onFulfilled =
        typeof onFulfilled === "function" ? onFulfilled : value => value;
    onRejected =
        typeof onRejected === "function" ? onRejected : reason => {
            throw reason;
        };

    // then裏面的FULFILLED/REJECTED狀態時 爲何要加setTimeout ?
    // 緣由:
    // 其一 2.2.4規範 要確保 onFulfilled 和 onRejected 方法異步執行(且應該在 then 方法被調用的那一輪事件循環以後的新執行棧中執行) 因此要在resolve里加上setTimeout
    // 其二 2.2.6規範 對於一個promise,它的then方法能夠調用屢次.(當在其餘程序中屢次調用同一個promise的then時 因爲以前狀態已經爲FULFILLED/REJECTED狀態,則會走的下面邏輯),因此要確保爲FULFILLED/REJECTED狀態後 也要異步執行onFulfilled/onRejected

    // 其二 2.2.6規範 也是resolve函數里加setTimeout的緣由
    // 總之都是 讓then方法異步執行 也就是確保onFulfilled/onRejected異步執行

    // 以下面這種情景 屢次調用p1.then
    // p1.then((value) => { // 此時p1.status 由pending狀態 => fulfilled狀態
    // console.log(value); // resolve
    // // console.log(p1.status); // fulfilled
    // p1.then(value => { // 再次p1.then 這時已經爲fulfilled狀態 走的是fulfilled狀態判斷裏的邏輯 因此咱們也要確保判斷裏面onFuilled異步執行
    // console.log(value); // 'resolve'
    // });
    // console.log('當前執行棧中同步代碼');
    // })
    // console.log('全局執行棧中同步代碼');
    //

    if (that.status === FULFILLED) { // 成功態
        return newPromise = new Promise((resolve, reject) => {
            setTimeout(() => {
                try{
                    let x = onFulfilled(that.value);
                    resolvePromise(newPromise, x, resolve, reject); // 新的promise resolve 上一個onFulfilled的返回值
                } catch(e) {
                    reject(e); // 捕獲前面onFulfilled中拋出的異常 then(onFulfilled, onRejected);
                }
            });
        })
    }

    if (that.status === REJECTED) { // 失敗態
        return newPromise = new Promise((resolve, reject) => {
            setTimeout(() => {
                try {
                    let x = onRejected(that.reason);
                    resolvePromise(newPromise, x, resolve, reject);
                } catch(e) {
                    reject(e);
                }
            });
        });
    }

    if (that.status === PENDING) { // 等待態
        // 當異步調用resolve/rejected時 將onFulfilled/onRejected收集暫存到集合中
        return newPromise = new Promise((resolve, reject) => {
            that.onFulfilledCallbacks.push((value) => {
                try {
                    let x = onFulfilled(value);
                    resolvePromise(newPromise, x, resolve, reject);
                } catch(e) {
                    reject(e);
                }
            });
            that.onRejectedCallbacks.push((reason) => {
                try {
                    let x = onRejected(reason);
                    resolvePromise(newPromise, x, resolve, reject);
                } catch(e) {
                    reject(e);
                }
            });
        });
    }
};

/** * Promise.all Promise進行並行處理 * 參數: promise對象組成的數組做爲參數 * 返回值: 返回一個Promise實例 * 當這個數組裏的全部promise對象所有變爲resolve狀態的時候,纔會resolve。 */
Promise.all = function(promises) {
    return new Promise((resolve, reject) => {
        let done = gen(promises.length, resolve);
        promises.forEach((promise, index) => {
            promise.then((value) => {
                done(index, value)
            }, reject)
        })
    })
}

function gen(length, resolve) {
    let count = 0;
    let values = [];
    return function(i, value) {
        values[i] = value;
        if (++count === length) {
            console.log(values);
            resolve(values);
        }
    }
}

/** * Promise.race * 參數: 接收 promise對象組成的數組做爲參數 * 返回值: 返回一個Promise實例 * 只要有一個promise對象進入 FulFilled 或者 Rejected 狀態的話,就會繼續進行後面的處理(取決於哪個更快) */
Promise.race = function(promises) {
    return new Promise((resolve, reject) => {
        promises.forEach((promise, index) => {
           promise.then(resolve, reject);
        });
    });
}

// 用於promise方法鏈時 捕獲前面onFulfilled/onRejected拋出的異常
Promise.prototype.catch = function(onRejected) {
    return this.then(null, onRejected);
}

Promise.resolve = function (value) {
    return new Promise(resolve => {
        resolve(value);
    });
}

Promise.reject = function (reason) {
    return new Promise((resolve, reject) => {
        reject(reason);
    });
}

/** * 基於Promise實現Deferred的 * Deferred和Promise的關係 * - Deferred 擁有 Promise * - Deferred 具有對 Promise的狀態進行操做的特權方法(resolve reject) * *參考jQuery.Deferred *url: http://api.jquery.com/category/deferred-object/ */
Promise.deferred = function() { // 延遲對象
    let defer = {};
    defer.promise = new Promise((resolve, reject) => {
        defer.resolve = resolve;
        defer.reject = reject;
    });
    return defer;
}

/** * Promise/A+規範測試 * npm i -g promises-aplus-tests * promises-aplus-tests Promise.js */

try {
  module.exports = Promise
} catch (e) {
}
複製代碼

github源碼地址:https://github.com/legend-li/Promise/blob/master/Promise.js

5.Promise測試

npm i -g promises-aplus-tests
promises-aplus-tests Promise.js
複製代碼

Tip: 歡迎到QQ羣583818653來交流前沿前端技術。咱們是一個大前端交流中心,幫助你們快速進階前端架構師
Vue相關交流,請來QQ羣366420656

6.相關知識參考資料

備註:原文地址

相關文章
相關標籤/搜索