手撕ES6--Promise

廢話不多說,直接上代碼

class MyPromise {
    constructor(fn) {

        this._succ_res = null;
        this._err_res = null;

        this.status = '';

        this.callback_arr = [];

        let that = this;

        fn(function (res) {
            that._succ_res = res;
            that.status = 'succ';
            if(that.callback_arr){
                that.callback_arr.forEach(element => {
                    element.fn1(res)
                });
            }
        }, function (err) {
            that._err_res = err;
            that.status = "error";
            if(that.callback_arr){
                that.callback_arr.forEach(element => {
                    element.fn2(err)
                });
            }
        })
    }


    then(fn1, fn2) {
        if (this.status === 'succ') {
            fn1(this._succ_res);
        } else if (this.status === 'error') {
            fn2(this._err_res)
        }else{
            this.callback_arr.push({fn1,fn2})
        }
    }


    static all(arr){
        return new MyPromise((resolve,reject)=>{

            let index = 0

            let result = []

            next();

            function next(){

                arr[index].then(function(res){
                    result.push(res)
                    index++;
                    if(index === arr.length){
                        resolve(result)
                    }else{
                        next()
                    }
                },reject)
            }
           
        })
    }

}


MyPromise.all([test(11,true),test(22)]).then(function(arr){
    console.log(arr)
},function(){
    console.log('失敗了')
})

//異步測試函數(shù)
function test(num,succ){
    return new MyPromise(function(resolve,reject){
        setTimeout(function(){
            if(succ){
                resolve(num)
            }else{
                reject()
            }
        },2000)
    });
}


test(66,true).then(function(res){
    console.log(res)
},function(){
    console.log('失敗了')
})

嗯,就是這樣的,隨手做了兩個測試,一點問題也沒有,代碼實現(xiàn)比較簡單,就不多說了.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,941評論 25 709
  • 不要在意別人背后怎么說你,怎么看你。因為這些言語改變不了事實,卻可以攪亂你的心,心如果亂了,一切都亂了。理解你的人...
    珍妮本閱讀 156評論 0 1
  • 早上五點三十三分開始晨間思,到六點十五分結(jié)束,四十分鐘的語音輸出,8200字左右。今天比昨天而言,又是一個進步。 ...
    潔_寞碎閱讀 195評論 0 0
  • 翻手為云 覆手為雨 多年不減你深情
    一只考拉z閱讀 472評論 0 2

友情鏈接更多精彩內(nèi)容