手写Promise

123 阅读1分钟

实现Promise主要几步:

  1. Promise的基本结构
  2. new一个实例,实例中传入参数,自动执行
  3. 三种状态的实现
  4. then的实现
  5. 异步的实现
  6. then的链式调用
class Commitment {
    static PENDING = '待定';
    static FULFILLED = '成功';
    static REJECT = '拒绝';
    constructor(func) { //类的构造函数,调用new的时候自动执行
        this.result = null; //resolve或者reject后向后传递的参数
        this.status = Commitment.PENDING;
        this.resolveCallbacks = [];
        this.rejectCallbacks = [];
        try {
            func(this.resolve.bind(this), this.reject.bind(this));
        } catch {
            this.reject(error);
        } //绑定内外部status的值
    }
    resolve(result) {
        setTimeout(() => {
            if (this.status === Commitment.PENDING) {
                this.status = Commitment.FULFILLED;
                this.result = result;
                this.resolveCallbacks.forEach(callback => {
                    callback(result);
                })
            }
        })
    }
    reject(result) {
            setTimeout(() => {
                if (this.status === Commitment.PENDING) {
                    this.status = Commitment.REJECT;
                    this.result = result;
                    this.rejectCallbacks.forEach(callback => {
                        callback(result)
                    })
                }
            })
        } //resolve,reject也是函数
    then(onFULFILLED, onREJECTED) {
        return new Commitment((resolve, reject) => {
                if (this.status === Commitment.PENDING) {
                    this.resolveCallbacks.push(onFULFILLED);
                    this.rejectCallbacks.push(onREJECTED);
                }
                if (this.status === Commitment.FULFILLED) {
                    setTimeout(() => {
                        onFULFILLED(this.status);
                    })
                }
                if (this.status === Commitment.REJECT) {
                    setTimeout(() => {
                        onREJECTED(this.status)
                    })
                }
            }) //可以传入两个参数,这两个参数都是函数,一个是当状态为成功的时候执行,一个是状态为失败的时候执行

    }
}