【问题标题】:Resolving Promise Outside解决外面的承诺
【发布时间】:2020-01-03 22:18:19
【问题描述】:

我正在尝试访问 promiseresolvereject 参数,以便我可以通过其他方法解决/拒绝它。

这是一个实现示例:

class TestClass {
  public readonly initialized: Promise<void> = new Promise((resolve, reject) => {
    console.log("initialized");
    this.resolver = resolve;
    console.log("this.resolver", this.resolver);
    this.rejector = reject;
  });
  private resolver: (value?: void | PromiseLike<void>) => void;
  private rejector: (value?: void | PromiseLike<void>) => void;
  public constructor() {
    console.log("constructor");
    console.log("this.resolver", this.resolver);
  }
  public load() {
    // Do stuff and call `this.resoler()` or `this.rejector()`.
  }
}

我这样做是为了等到一些内部组件准备好将类实例标记为已初始化:

public async componentDidMount() {
  await testClass.initialized;
  // Do stuff.
}

我遇到的问题取决于我测试运行此代码的位置,this.resolver 仍然是undefined

使用 TypeScript 3.7.3 在我的 React 应用程序中运行此代码,我得到:

initialized
this.resolver ƒ () { [native code] }
constructor
this.resolver undefined

但是,在 TypeScript Playground 中针对最高版本 3.7.2 运行它,我得到了预期的结果:

initialized
this.resolver ƒ () { [native code] }
constructor
this.resolver ƒ () { [native code] }

我很难理解为什么 this.resolver 在我的 React 应用程序中是 undefined,但相同的代码在在线游乐场中也能正常工作。

【问题讨论】:

  • TestClass 是 React 组件吗?
  • @Eldar 不,TestClass 不是 React 组件。
  • 在构造函数中执行初始化。

标签: typescript promise


【解决方案1】:

你不应该有 initialized 方法,而只是在构造函数中运行它:

class TestClass {
  public readonly initialized: Promise<void>;
  private resolver: (value?: void | PromiseLike<void>) => void;
  private rejector: (value?: void | PromiseLike<void>) => void;

  public constructor() {
    this.initialized = new Promise((resolve, reject) => {
      this.resolver = resolve;
      this.rejector = reject;
    });
  }

  public load() {
    // Do stuff and call `this.resoler()` or `this.rejector()`.
  }
}

【讨论】:

  • 将它移到构造函数可以解决问题。对于为什么代码在某些 TypeScript 解释器中有效,而在其他解释器中无效,我仍然摸不着头脑。在我看来,它应该在任何地方都有效。
  • 可能在 tsconfig 中使用了旧的/不同的 ES lib?
猜你喜欢
  • 1970-01-01
  • 2015-06-24
  • 2018-04-02
  • 2019-09-29
  • 1970-01-01
  • 2014-08-10
  • 2020-03-16
  • 2022-12-05
  • 1970-01-01
相关资源
最近更新 更多