promise 语法实现

357 阅读1分钟

原理

promise((resolve,reject)=>{}).then(callback).catch(callback);
初始化传入resolve、reject并执行runner,然后执行then将链式调用的函数保存在对象内部,最后runner内部通过resolve执行回调

实现


class customPromise {
    state = "pending";
    resolveCallback = null;
    rejectCallback = null;
    
    constructor(runner) {
        runner(this.resolve.bind(this), this.reject.bind(this));
    }
    
    then(callback) {
        this.resolveCallback = callback;
    }
    
    catch(callback) {
        this.rejectCallback = callback;
    }
    
    resolve(...args) {
        this.state = "finished";
        if (this.resolveCallback instanceof Function) {
            this.resolveCallback(...args);
        }
    }
    
    reject(...args) {
        this.state = "error";
        if (this.rejectCallback instanceof Function) {
            this.rejectCallback(...args);
        }
    }
}