嘗試手寫promise

joshinrai發表於2019-07-17

promise特性

    Promise捕獲錯誤與 try catch 等同
    Promise 擁有狀態變化
    Promise 方法中的回撥是非同步的
    Promise 會儲存返回值
    Promise 方法每次都返回一個新的Promise
複製程式碼
  • Promise 實現 遵循promise/A+規範

  • Promise/A+規範譯文:

  • malcolmyu.github.io/2015/06/12/…

     // 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) {
                     // 只能由pedning狀態 => 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) {
                     // 只能由pedning狀態 => 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 由pedding狀態 => 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) {
     }
    複製程式碼

相關文章