【笔记】实现一个简易的Promise

const PENDING_STATE = "pending";
const FULLFILL_STATE = "fullfilled";
const REJECTED_STATE = "refected";

class Promise {
  constructor(executor) {
    if (typeof executor !== "function") {
      throw new Error("Promise executor must be a function.");
    }
    this.__state = PENDING_STATE;
    this.__chains = [];

    const resolve = res => {
      // 当且仅当状态是 pending 状态时才可以调用resolve或者reject,防止二次调用。
      if (this.__state !== PENDING_STATE) return;

      // resolve要处理promise,判断是否有then属性
      if (res && typeof res.then === "function") {
        return res.then();
      }

      this.__state = FULLFILL_STATE;
      this.__internalValue = res;

      for (const { onFullFilled } of this.__chains) {
        onFullFilled(res);
      }
    };

    const reject = err => {
      if (this.__state !== PENDING_STATE) return;
      this.__state = REJECTED_STATE;
      this.__internalValue = err;

      for (const { onRejected } of this.__chains) {
        onRejected(err);
      }
    };

    // 规范中,Promise初始化就调用executor
    try {
      executor(resolve, reject);
    } catch (err) {
      // 如果处理器函数抛出一个同步错误,我们认为这是一个失败状态
      reject(err);
    }
  }

  then(onFullFilled, onRejected) {
    return new Promise((resolve, reject) => {
      // 参考上述的constructor实现
      const _onFullFilled = res => {
        try {
          resolve(onFullFilled(res));
        } catch (err) {
          reject(err);
        }
      };

      const _onRejected = err => {
        try {
          reject(onRejected(res));
        } catch (err) {
          reject(err);
        }
      };

      if (this.__state === FULLFILL_STATE) {
        _onFullFilled(this.__internalValue);
      } else if (this.__state === REJECTED_STATE) {
        _onRejected(this.__internalValue);
      } else {
        this.__chains.push({
          onFullFilled: _onFullFilled,
          onRejected: _onRejected
        });
      }
    });
  }
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

扫码关注云+社区

领取腾讯云代金券