1. 程式人生 > >初步了解 promise-02 簡單手寫源碼

初步了解 promise-02 簡單手寫源碼

成功 設置 ros fill 失敗 lba led log func

廢話不多說·· 直接上 簡單手寫 promise 源碼

/**
 *@ 簡單手寫 prosmise 方法
 */

const enum_pending = "pending";
const enum_resolved = "resolved";
const enum_rejected = "rejected";

function Promise(executor) {
    let selt = this;
    //初始化狀態
    selt.value = undefined;
    selt.reason = undefined;
    selt.status = enum_pending;

    //定義存放then成功的回調數組
    selt.onResolvedCallbacks = [];
    selt.onRejectedCallbacks = [];

    //成功執行
    function resolve(value) {
        //等待的狀態(pending)才可以執行 並設置成功的狀態
        if (selt.status === enum_pending) {
            selt.value = value;
            selt.status = enum_resolved;
            selt.onResolvedCallbacks.forEach(fn => fn());
        }
    }

    //失敗執行
    function reject(reason) {
        //等待的狀態(pending)才可以執行 並設置失敗的狀態
        if (selt.status===enum_pending){
            selt.reason= reason;
            selt.status=enum_rejected;
            selt.onRejectedCallbacks.forEach(fn=>fn());
        }
    }
    //異常就走失敗
    try {
        executor(resolve,reject);
    }catch (e) {
        reject(e);
    }

};
//定義 promise then 方法
Promise.prototype.then = function (onFulfilled, onRejected) {
    let self = this;
    //根據狀態執行對應的方法
    if (self.status === enum_resolved) {
        onFulfilled(self.value);
    }
    if (self.status === enum_rejected) {
        onRejected(self.value);
    }
    if (self.status === enum_pending) {
        //保存回調函數
        self.onResolvedCallbacks.push(() => {
            onFulfilled(self.value);
        });
        self.onRejectedCallbacks.push(() => {
            onRejected(self.value);
        })
    }

}

module.exports = Promise;

  調用:

let Promise = require("./01.promise");

let promise = new Promise((resolve,reject)=>{
    resolve()
})

promise.then((data)=>{
    console.log("成功·");
},(err)=>{
    console.log("失敗·");
});

  

初步了解 promise-02 簡單手寫源碼