一步步解析Promise

2022-03-24  本文已影响0人  wyc0859
class Promise {
  public x!: number;
  constructor(ParamFun: (x: number) => any) {
    console.log("类构造函数");
    this.x = 88;
    ParamFun(this.x);
  }
}

new Promise(function (p1: number): any {
  console.log("实例参数函数的参数p1:", p1); //p1: 88
});

new Promise(a函数) -> 构造函数(ParamFun=a函数)
构造函数类运行a函数(),需要参数1
所以this.x有值后,传入做参数,然后外面的new Promise(a函数(得到了参数this.x))


把上面x的类型改成函数

type pfun = (ok: any) => any; //定义函数类型
class PromiseX {
  public x!: pfun;
  constructor(ParamFun: (x: pfun) => any) {
    console.log("类构造函数");
    this.x = (ok: any): any => {
      console.log("A函数的参数1-是我B函数,我的参数是:", ok);
    };
    ParamFun(this.x);
  }
}

new PromiseX(function (p1: pfun): any {
  console.log("实例参数函数A-的参数p1:");
  p1("abc");
});
// 执行结果为:
// 类构造函数
// 实例参数函数A-的参数p1:
// A函数的参数1-是我B函数,我的参数是: abc

继续改造上面的函数,把参数x改成2个参数:resolve,reject,类型还是函数,就是Promise雏形

上一篇 下一篇

猜你喜欢

热点阅读