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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,926评论 25 709
  • 不要在意别人背后怎么说你,怎么看你。因为这些言语改变不了事实,却可以搅乱你的心,心如果乱了,一切都乱了。理解你的人...
    珍妮本阅读 149评论 0 1
  • 早上五点三十三分开始晨间思,到六点十五分结束,四十分钟的语音输出,8200字左右。今天比昨天而言,又是一个进步。 ...
    洁_寞碎阅读 136评论 0 0
  • 翻手为云 覆手为雨 多年不减你深情
    一只考拉z阅读 459评论 0 2