淺析Promise原理

Promise原型對象

在瀏覽器控制檯輸入如下代碼,可以看到Promise原型對象信息。

var p = new Promise(()=>{});
console.log(p)

Promise原型
Promise原型上有catchfinallythen等方法。同時Promise內部維護了兩個屬性值statusvalue

Promise構造方法

再看Promise的構造方法,如下圖
在這裏插入圖片描述
構造函數有allallSettledfinallyracerejectresolve等方法。

簡單實現

構造函數實現總結:

  1. 構造函數接受一個函數executor,並立即執行;
  2. executor函數接受兩個參數,一個是resolve函數,一個是rejected函數,用於後續回調執行;
  3. promise對象的then方法中的第一個參數(函數)是狀態變爲fulfilled時的回調。
  4. resolve函數被調用時,會觸發then方法中的回調函數的指定。
const PENDING = 'pending';
const FULFILLED = 'fullfilled';
const REJECTED = 'rejected';
function Promise(executor) {
  this.status = PENDING;
  this.value = undefined;

  this.onResolvedCallback = []; //成功狀態下的回調函數集合
  this.onRejectedCallback = [];

  function resolve(value) {
  };
  
  function reject() {
  };
  
  executor(resolve, reject);
}
const PENDING = 'pending';
const FULFILLED = 'fullfilled';
const REJECTED = 'rejected';
function Promise(executor) {
  this.status = PENDING;
  this.value = undefined;

  this.onResolvedCallback = []; //成功狀態下的回調函數集合
  this.onRejectedCallback = [];

  function resolve(value) {
    if(this.status === PENDING) {
      this.status = FULFILLED;
      this.value = value;
      // 觸發後續then方法中的回調方法執行
      onRejectedCallback.forEach(onResolved => {
        onResolved(value)
      });
    }
  };
  
  function reject() {
  };
  
  try { // 考慮到執行executor的過程中有可能出錯,所以我們用try/catch塊給包起來,並且在出錯後以catch到的值reject掉這個Promise
    executor(resolve, reject) // 執行executor
  } catch(e) {
    reject(e)
  }
}
``

參考

https://www.jianshu.com/p/b4f0425b22a1
https://github.com/xieranmaya/blog/issues/3

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章