使用typescript实现Promise

/**
 * @name         MyPromise
 * @description  简单实现Promise
 * @author       ****
 */
class MyPromise<T> {
  //存放成功的回调函数
  private resolveFn: Function = () => {};
  //存放失败的回调函数
  private rejectFn: Function = () => {};
  // 当前的状态
  // 有三种状态 pending 为初始状态 pending 状态一旦修改 无法在进行改变
  private status: string = "pending";
  // 存放传入的值
  private value: any;
  // race的状态
  static raceStatus: string = "pending";

  constructor(props: Function) {
    //修改this指向 将this实例后的实体
    props(this.resolve.bind(this), this.reject.bind(this));
  }
  /**成功的方法 用于修改状态和值  异步成功以后 将then 传进来的回调 进行调用 */
  public resolve(value: string | object | Array<any>, isRace: boolean) {
    if (MyPromise.raceStatus === "pending" && isRace)
      MyPromise.raceStatus = "success";
    if (this.status === "pending")
      (this.value = value), (this.status = "success");
    // if (this.status === "pending")this.status = "success" ;
    if (this.status === "success") this.resolveFn(this.value);
  }
  /**失败的方法 用于修改状态和值  异步失败以后 将cath 传进来的回调 进行调用 */
  public reject(value: string | object | Array<any>, isRace: boolean) {
    if (MyPromise.raceStatus === "pending" && isRace)
      MyPromise.raceStatus = "error";
    if (this.status === "pending") this.value = value;
    if (this.status === "pending") this.status = "error";
    if (this.status === "error") this.rejectFn(this.value);
  }
  /**存储成功或失败的回调函数 return this 实现链式调用  存储函数 异步调用*/
  public then(success: Function, error?: Function) {
    if (this.status === "success") {
      success(this.status);
    } else if (this.status === "pending") {
      this.resolveFn = success;
    }
    if (this.status === "error" && error) {
      error(this.value);
    } else if (this.status === "pending" && error) {
      this.rejectFn = error;
    }
    return this;
  }
  /**存储成功或失败的回调函数 return this 实现链式调用  存储函数 异步调用*/
  public catch(error: Function) {
    if (this.status === "error") error(this.value);
    return this;
  }
  /**
   * @description 将 Promise数组 所有的 都完成以后 回调
   * @param    {Array} arr   Promise 的 数组
   * @returns  {Promise}
   */
  static all(arr: Array<MyPromise<any>>) {
    let resArr: Array<any> = [];
    return new MyPromise((resolve: Function, reject: Function) => {
      arr.forEach((item) => {
        item.then(
          (res: any) => {
            resArr.push(res);
            if (resArr.length === arr.length) {
              resolve(resArr);
            }
          },
          (err: any) => {
            reject(err);
          }
        );
      });
    });
  }
  // 静态属性不用实例直接调用  Mypromise.resolve("123")
  static resolve() {
    // return this;
  }
  // 静态属性不用实例直接调用  Mypromise.reject("123")
  static reject() {
    // return this;
  }
  /**
   * @description Promise 数组 最先完成的那个进行回调
   * @param  {Array} arr   Promise 的 数组
   * @returns {Promise} Promise
   */
  static reace(arr: Array<MyPromise<any>>) {
    return new MyPromise((resolve: Function, reject: Function) => {
      arr.forEach((item) => {
        item.then(
          (res: any) => {
            if (MyPromise.raceStatus === "pending") resolve(res, true);
          },
          (err: any) => {
            if (MyPromise.raceStatus === "pending") reject(err, true);
          }
        );
      });
    });
  }
}

(function () {
  let a: MyPromise<string> = new MyPromise(
    (resolve: Function, reject: Function) => {
      setTimeout(() => {
        resolve("结果");
        // reject("失败");
      }, 1000);
    }
  );
  a.then(
    (res: any) => {
      console.log(res);
    },
    (err: any) => {
      console.log(err);
    }
  );

  let p1: MyPromise<String> = new MyPromise((res: Function, rej: Function) => {
    setTimeout(() => {
      res("快的结果");
    }, 1000);
  });
  let p2: MyPromise<String> = new MyPromise((res: Function, rej: Function) => {
    setTimeout(() => {
      res("慢的结果");
    }, 10000);
  });
  MyPromise.all([p1, p2]).then((res: Array<any>) => {
    console.log(res);
  });
  MyPromise.reace([p1, p2]).then((res: any) => {
    console.log(res);
  });
})();

posted @   spongeCoder  阅读(264)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示