【发布时间】:2020-01-03 22:18:19
【问题描述】:
我正在尝试访问 promise 的 resolve 和 reject 参数,以便我可以通过其他方法解决/拒绝它。
这是一个实现示例:
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