手撕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('失败了')
})

//异步测试函数
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('失败了')
})

嗯,就是这样的,随手做了两个测试,一点问题也没有,代码实现比较简单,就不多说了.

你可能感兴趣的:(手撕ES6--Promise)