【手撕原理】面試官:來吧,手寫一個簡單版的 Promise

重新實現Promise.js

class myPromise{
    constructor(exc){
      //不能相信用戶的輸入,所以這裏要做參數效驗
        if(typeof exc !== 'function'){
            throw new TypeError('this is not a function!')
        }
        this.initValue();
        this.initBind();
        exc(this.resolve,this.reject);
    }
    //進行代碼的優化&初始化
    initValue(){
    	//記錄狀態和值的改變
        //初始化值
        this.state = 'pending';  //初始狀態
        this.value = null;  //終值
        this.reason = null; //據因
    }
    //綁定 this
    initBind(){
        this.resolve = this.resolve.bind(this);
        this.reject = this.reject.bind(this);
    }
     //成功後的一系列操作(狀態的改變,成功回調的執行)
    resolve(value){
        if(this.state === 'pending'){
            this.state = 'resolve'; //狀態進行改變
            this.value = value; //執行成功的回調,把終值進行賦值
        }
    }
    reject(reason){
    //失敗後的一系列操作(狀態的改變,失敗回調的執行)
        if(this.state === 'pending'){
            this.state = 'reject'; //狀態進行改變
            this.reason = reason; //執行成功的回調,把據因進行賦值
        }
    }
    then(resolve,reject){
    //  參數效驗
        if(typeof resolve !== 'function'){
            resolve = function(value){
                return value;
            }
        }
        if(typeof reject !== 'function'){
            reject = function(reason){
                throw reason;
            }
        }
        if(this.state === 'resolve'){
            resolve(this.value);
        }
        if(this.state === 'reject'){
            reject(this.reason);
        }
    }
}
module.exports = myPromise;

test.js

const myPromise = require('./重新實現Promise')

new myPromise((resolve,reject)=>{
    console.log('it is good');
    resolve(1);
}).then(value=>{
    console.log('value',value);
},reason=>{
    console.log('reason',reason);
})
學如逆水行舟,不進則退
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章