使用 TS 和 class 实现一个简易 Promise

前言

最近在看书学习的过程中,发现自己对 Promise 以及宏任务、微任务之间的关系还掌握得不够熟练,于是决定学习百家之长,自己动手实现一个 Promise,当然,就算如今这种行为已经烂了大街,我也想特立独行一些,于是就用上了 typescript 和 class。

基本接口

首要的就是 Promise 独一无二的三个状态

type StatusType = 'pending' | 'fulfilled' | 'rejected';

然后是声明时需要传入的函数 executor

interface OnfulfilledType<T = unknown> {
  (v?: T): unknown;
}

interface OnrejectedType {
  (e?: Error): unknown;
}

interface ExecutorType<T = unknown> {
  (resolve: OnfulfilledType<T>, reject: OnrejectedType): void;
}

这时候,我们就可以声明一个简单的 IPromise Class 了

class IPromise<T = unknown> {
    constructor(executor?: ExecutorType<T>) {
      // 为了尽量还原,所以 status 等属性不声明在 IPromise 对象上,这样就不会暴露出去
      let status: StatusType = 'pending'; // 唯一状态
      let value: unknown = null; // resolve 接收的值
      let reason: Error = new Error('IPromise Error'); // reject 接收的值

    const resolve: OnfulfilledType<T> = (v) => {
      if (status === 'pending') {
        status = 'fulfilled';
        value = v;
      }
    };

    const reject: OnrejectedType = (e) => {
      if (status === 'pending') {
        status = 'rejected';
        if (e && isError(e)) {
          reason = e;
        } else {
          throw new Error('IPromise reason should be Error Type');
        }
      }
    };

    if (executor) {
      try {
        executor(resolve, reject);
      } catch (error) {
        reject(error);
      }
    }
  }
}

new 一个对象试试

const promise: IPromise<string> = new IPromise((resolve) => {
  resolve('promise'); // 这里如果传入 number 类型的参数会报错
});

好了,热身完成,开始真正实现 IPromise 的功能了。

完整实现

想了想,Promise 对象有什么功能呢

then

  1. 获取 Promise 对象声明时 resolve 或 reject 出的值
  2. 可以接受两个函数作为可选参数
  3. 将 then 中的函数放入下一个微任务中执行
  4. 链式调用
  5. 多个 then 同时调用
  6. Promise 穿透,即如果 then 接收的参数不是函数,则决议结果会穿透到下一个 then 中

catch

  1. 获取 reject 出的值
  2. 链式调用
  3. 多个 catch 同时调用
  4. Promise 穿透

resolve

返回一个状态为 fulfilled 的 Promise 实例

reject

返回一个状态为 rejected 的 Promise 实例

all

接收一个 Promise 实例数组,并返回一个 resolve 出所有结果的 Promise 实例,有一个实例决议为 rejected,则会 reject 出错误

race

接收一个 Promise 实例数组,并返回一个 resolve 出首个结果的 Promise 实例

其中,resolve,reject,all 和 race 为 Promise 对象私有方法,不会被实例继承,所以用 static 实现

盘他!

type StatusType = 'pending' | 'fulfilled' | 'rejected';

interface OnfulfilledType<T = unknown> {
  (v?: T): unknown;
}

interface OnrejectedType {
  (e?: Error): unknown;
}

interface ExecutorType<T = unknown> {
  (resolve: OnfulfilledType<T>, reject: OnrejectedType): void;
}

interface ResolvePromiseType {
  (promise: IPromise, result: unknown, resolve: OnfulfilledType, reject: OnrejectedType): void;
}

const isFn = (fn: unknown) => typeof fn === 'function';

const isError = (e: unknown) => e instanceof Error;

const onCorrect: OnfulfilledType = (v) => v;

const one rror: OnrejectedType = (e) => {
  throw e;
};

const handleFnList = (fnList: Function[]) => {
  if (fnList.length) fnList.forEach((fn) => fn());
};

const resolvePromise: ResolvePromiseType = (promise, result, resolve, reject) => {
  if (result === promise) {
    reject(new Error('Chaining cycle detected for promise #<Promise>'));
  } else if (result instanceof IPromise) {
    result.then(resolve, reject);
  } else resolve(result);
};

class IPromise<T = unknown> {
  static resolve = (v: unknown) => {
    if (v instanceof IPromise) return v;
    return new IPromise((resolve) => resolve(v));
  };

  static reject = (e: Error) => {
    return new IPromise((_, reject) => {
      if (isError(e)) reject(e);
      else {
        throw new TypeError('IPromise reason should be Error Type');
      }
    });
  };

  static all = (promiseList?: IPromise[]) => {
    if (!Array.isArray(promiseList)) throw new TypeError('The argument should be an array!');
    return new IPromise((resolve, reject) => {
      try {
        const results: unknown[] = [];
        promiseList.forEach((promise) => {
          if (promise instanceof IPromise) {
            promise.then((v) => {
              results.push(v);
              if (results.length === promiseList.length) resolve(results);
            });
          } else reject(new TypeError('Every item of argument should be IPromise!'));
        });
      } catch (error) {
        reject(error);
      }
    });
  };

  static race = (promiseList?: IPromise[]) => {
    if (!Array.isArray(promiseList)) throw new TypeError('The argument should be an array!');
    return new IPromise((resolve, reject) => {
      try {
        const result: unknown[] = [];
        promiseList.forEach((promise) => {
          if (promise instanceof IPromise) {
            promise.then((v) => {
              if (!result.length) result.push(v);
              else resolve(result[0]);
            });
          } else reject(new TypeError('Every item of argument should be IPromise!'));
        });
      } catch (error) {
        reject(error);
      }
    });
  };

  then: (onfulfilled?: OnfulfilledType, onRejected?: OnrejectedType) => IPromise;
  catch: (catchFn: OnrejectedType) => IPromise;

  constructor(executor: ExecutorType<T>) {
    let status: StatusType = 'pending'; // 唯一状态
    let value: unknown = null; // resolve 接收的值
    let reason: Error = new Error('IPromise Error'); // reject 接收的值
    // 如果初始化时的 resolve 是异步,则用数组来保存需要执行的方法
    const onfulfilledList: OnfulfilledType[] = [];
    const onrejectedList: OnrejectedType[] = [];

    this.then = (onfulfilled = onCorrect, onRejected = one rror) => {
      const promise = new IPromise((resolve, reject) => {
        const f = isFn(onfulfilled) ? onfulfilled : onCorrect;
        const r = isFn(onRejected) ? onRejected : one rror;

        const newF = () => {
          queueMicrotask(() => {
            try {
              resolvePromise(promise, f(value), resolve, reject);
            } catch (error) {
              reject(error);
            }
          });
        };

        const newR = () => {
          queueMicrotask(() => {
            try {
              resolvePromise(promise, r(reason), resolve, reject);
            } catch (error) {
              reject(error);
            }
          });
        };

        if (status === 'fulfilled') newF();
        if (status === 'rejected') newR();
        if (status === 'pending') {
          onfulfilledList.push(newF);
          onrejectedList.push(newR);
        }
      });

      return promise;
    };

    this.catch = (catchFn) => this.then(undefined, catchFn);

    const resolve: OnfulfilledType<T> = (v) => {
      if (status === 'pending') {
        status = 'fulfilled';
        value = v;
        handleFnList(onfulfilledList);
      }
    };

    const reject: OnrejectedType = (e) => {
      if (status === 'pending') {
        status = 'rejected';
        if (e && isError(e)) {
          reason = e;
          handleFnList(onrejectedList);
        } else {
          throw new Error('IPromise reason should be Error Type');
        }
      }
    };

    if (executor) {
      if (isFn(executor)) {
        try {
          executor(resolve, reject);
        } catch (error) {
          reject(error);
        }
      } else reject(new TypeError('new IPromise() should receive a Function argument!'));
    } else reject(new Error('new IPromise() should receive an arguments!'));
  }
}

export default IPromise;

上一篇:React中如何在componentWillUnmount中取消之前的Promise异步请求?


下一篇:《Promise学习笔记》-1Promise基本使用