class myPromise {
  callbacks = [];
  state = 'pending';
  value = null;
  constructor(fn) {
    // 这里的参数多了一个_reject函数
    fn(this._resolve.bind(this), this._reject.bind(this));
  }
  then(onFulfilled, onRejected) {
    return new myPromise((resolve, reject) => {
      // 这里增加了一部分代码
      this._handle({
        onFulfilled: onFulfilled || null,
        onRejected: onRejected || null,
        resolve: resolve,
        reject: reject
      });
    });
  }
  _handle(callback) {
    if (this.state === 'pending') {
      this.callbacks.push(callback);
      return;
    }

    // 这里和上个版本的逻辑类似, 只不过增加了 rejected 状态
    let cb = this.state === 'fulfilled' ? callback.onFulfilled : callback.onRejected;

    if (!cb) {
      cb = this.state === 'fulfilled' ? callback.resolve : callback.reject;
      cb(this.value);
      return;
    }

    /**
     * cb函数在执行过程中可能会遇到报错, 如
     * promise.then(()=>{
     *    throw Error("error!")
     * })
     * 这时应当执行reject, 并将error信息传递出去
     */
    let ret;
    try {
      ret = cb(this.value);
      cb = this.state === 'fulfilled' ? callback.resolve : callback.reject;
    } catch (error) {
      ret = error;
      cb = callback.reject
    } finally {
      cb(ret);
    }

  }
  _resolve(value) {
    if (this.state !== 'pending') return

    if (value && (typeof value === 'object' || typeof value === 'function')) {
      var then = value.then;
      if (typeof then === 'function') {
        then.call(value, this._resolve.bind(this), this._reject.bind(this));
        return;
      }
    }

    this.state = 'fulfilled';//改变状态
    this.value = value;//保存结果
    this.callbacks.forEach(callback => this._handle(callback));
  }
  // 增加了_reject内部方法
  _reject(error) {
    if (this.state !== 'pending') return

    /**
     * 这里没有对error是不是promise的判断, 因此当onRejected函数返回一个promise实例时,会直接将这个实例传递出去,如
     *  new myPromise((res, rej) => {
          // 将一个promise实例传入rej()函数中
          rej(new myPromise(() => {console.log("test")}));  
        }).then(() => { }, data => {
          console.log(data);  // 这里将打印出上面的promise实例
        })
     */
    this.state = 'rejected';
    this.value = error;
    this.callbacks.forEach(callback => this._handle(callback));
  }
}
    function fn(resolve) {
        setTimeout(() => {
            resolve(1);
        }, 1000);
    };


    const myPromise1 = new myPromise(fn);
    myPromise1.then((res) => {
        console.log(res);
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(2);
            }, 1000);
        });
    }).then(res => {
        console.log(res);
    })


javascript

rejected 状态的补充


class myPromise {
  callbacks = [];
  state = 'pending';
  value = null;
  constructor(fn) {
    // 这里的参数多了一个_reject函数
    fn(this._resolve.bind(this), this._reject.bind(this));
  }
  then(onFulfilled, onRejected) {
    return new myPromise((resolve, reject) => {
      // 这里增加了一部分代码
      this._handle({
        onFulfilled: onFulfilled || null,
        onRejected: onRejected || null,
        resolve: resolve,
        reject: reject
      });
    });
  }
  _handle(callback) {
    if (this.state === 'pending') {
      this.callbacks.push(callback);
      return;
    }

    // 这里和上个版本的逻辑类似, 只不过增加了 rejected 状态
    let cb = this.state === 'fulfilled' ? callback.onFulfilled : callback.onRejected;

    if (!cb) {
      cb = this.state === 'fulfilled' ? callback.resolve : callback.reject;
      cb(this.value);
      return;
    }

    /**
     * cb函数在执行过程中可能会遇到报错, 如
     * promise.then(()=>{
     *    throw Error("error!")
     * })
     * 这时应当执行reject, 并将error信息传递出去
     */
    let ret;
    try {
      ret = cb(this.value);
      cb = this.state === 'fulfilled' ? callback.resolve : callback.reject;
    } catch (error) {
      ret = error;
      cb = callback.reject
    } finally {
      cb(ret);
    }

  }
  _resolve(value) {
    if (this.state !== 'pending') return

    if (value && (typeof value === 'object' || typeof value === 'function')) {
      var then = value.then;
      if (typeof then === 'function') {
        then.call(value, this._resolve.bind(this), this._reject.bind(this));
        return;
      }
    }

    this.state = 'fulfilled';//改变状态
    this.value = value;//保存结果
    this.callbacks.forEach(callback => this._handle(callback));
  }
  // 增加了_reject内部方法
  _reject(error) {
    if (this.state !== 'pending') return

    /**
     * 这里没有对error是不是promise的判断, 因此当onRejected函数返回一个promise实例时,会直接将这个实例传递出去,如
     *  new myPromise((res, rej) => {
          // 将一个promise实例传入rej()函数中
          rej(new myPromise(() => {console.log("test")}));  
        }).then(() => { }, data => {
          console.log(data);  // 这里将打印出上面的promise实例
        })
     */
    this.state = 'rejected';
    this.value = error;
    this.callbacks.forEach(callback => this._handle(callback));
  }
}
javascript

评论
avatar
0 评论
目录