当前位置:   article > 正文

使用 TS 和 class 实现一个简易 Promise_ts promise resolve

ts promise resolve

前言

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

基本接口

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

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

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

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

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

interface ExecutorType<T = unknown> {
  (resolve: OnfulfilledType<T>, reject: OnrejectedType): void;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

这时候,我们就可以声明一个简单的 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);
      }
    }
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

new 一个对象试试

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

好了,热身完成,开始真正实现 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 onError: 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 = onError) => {
      const promise = new IPromise((resolve, reject) => {
        const f = isFn(onfulfilled) ? onfulfilled : onCorrect;
        const r = isFn(onRejected) ? onRejected : onError;

        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;



  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/92129
推荐阅读
相关标签
  

闽ICP备14008679号