如何封裝Promise對象?

最近看到了一個有趣的Promise的方法,這裏記錄下來node

  {
          // state改變,resolve調用就會失敗
          if (this.state === "pending") {
            this.value = value;
            //resolve調用後,state轉爲fulfilled
            this.state = "fulfilled";
            // 一旦resolve執行,調用成功數組的函數
            this.onResolvedCallbacks.forEach(function (fn) {
              return fn(value);
            });
            //也可使用es6語法 簡寫
            //this.onResolvedCallbacks.forEach(fn => fn(value));
          }
        };
        let reject = (reason) => {
          // state改變,reject調用就會失敗
          if (this.state === "pending") {
            this.reason = reason;
            // reject調用後,state轉爲失敗狀態
            this.state = "rejected";
            // 一旦reject執行,調用失敗數組的函數
            this.onRejectedCallbacks.forEach(fn => fn(reason)); //簡寫
          }
        };

        // new MyPromise後的實例具備狀態, 默認狀態是等待,當執行器調用resolve後, 實例狀態爲成功狀態;當執行器調用reject後,實例狀態爲失敗狀態
        try {
          executor(resolve, reject);
        } catch (error) {
          reject(error);
        }
      }

      // then中有兩個參數 ,把第一個參數叫作then的成功回調,把第二個參數叫作then的失敗回調,這兩個參數也都是函數,當執行器調用resolve後,then中第一個參數函數會執行,當執行器調用reject後,then中第二個參數函數會執行
      then(onFulfilled, onRejected) {
        // 狀態爲fulfilled,執行onFulfilled,傳入成功的值
        if (this.state === "fulfilled") {
          onFulfilled(this.value);
        }
        // 狀態爲rejected,執行onRejected,傳入失敗的緣由
        if (this.state === "rejected") {
          onRejected(this.reason);
        }
        // 狀態爲pending時 
        if (this.state === "pending") {
          // onFulfilled傳入到成功數組
          this.onResolvedCallbacks.push(onFulfilled);
          // onRejected傳入到失敗數組
          this.onRejectedCallbacks.push(onRejected);
        }
      }
    }
	//當new MyPromise實例 會當即調用constructor(executor)
    let p = new MyPromise((resolve, reject) => {
      console.log("開始");
      setTimeout(function () {
        resolve("我成功了");
      }, 2000);
    });
    
    p.then(
      (resolve) => {
        console.log("success:" + resolve);
      },
      (reject) => {
        console.log("error:" + reject);
      }
    );
    console.log("結束");" _ue_custom_node_="true">
相關文章
相關標籤/搜索