【笔记】实现一个简易的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
        });
      }
    });
  }
}

 

转载于:https://www.cnblogs.com/smileSmith/p/8920234.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值