html5

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

2019-07-15  本文已影响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

上一篇下一篇

猜你喜欢

热点阅读