美文网首页html5
ts实现一个promise类(未完成)

ts实现一个promise类(未完成)

作者: 前端小旋风 | 来源:发表于2019-07-15 15:37 被阅读0次
    class MyPromise{
    
    
        private state:string = 'pending';
        private resolveFn:(res) => void;
        private rejectFn:(error) => void;
        private res:any = null;
        private error:any = null;
    
    
        constructor(fn:(r,j) => void){
            this.resolve = this.resolve.bind(this)
            this.reject = this.reject.bind(this)
            fn(this.resolve,this.reject)
        }
    
        private resolve(res){
            this.state = 'resolve';
            this.res = res;
            if(this.resolveFn){
                this.resolveFn(res);
            }
        }
    
        private reject(error){
            this.state = 'reject';
            this.error = error;
            if(this.rejectFn){
                this.rejectFn(error);
            }
        }
    
        public then(fn:(res) => void):MyPromise{
            if(this.state == 'resolve'){
                fn(this.res)
            }else if(this.state == 'pending'){
                this.resolveFn = fn;
            }
            return this;
        }
    
        public catch(fn:(error) => void):MyPromise{
            if(this.state == 'reject'){
                fn(this.error)
            }else if(this.state == 'pending'){
                this.rejectFn = fn;
            }
            return this;
        }
    
        static all(fnArray:Array<() => any>){
    
        }
    
    }
    

    调用方法

    new MyPromise((r,j) => {
        setTimeout(() => {
            j('@');
        }, 1000);
    }).then(res => {
        console.log(res,'@')
    }).catch(error => {
        console.log(error,'!')
    })
    

    我建了一个前端微信交流群,欢迎大家加入,qq中转群号:1076484243

    相关文章

      网友评论

        本文标题:ts实现一个promise类(未完成)

        本文链接:https://www.haomeiwen.com/subject/cfbnkctx.html