You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript构造函数中如何将Promise结果赋值给类变量?

问题原因

这是因为Promise是异步操作,构造函数是同步执行的。当你在构造函数里调用console.log(this.teste1)和console.log(this.teste2)时,数据库查询的Promise还没完成,then回调里的赋值代码还没执行,所以变量还是undefined。而then里的console.log能正常输出,是因为它要等数据库查询完成后才会触发。

解决方案

方法一:改用异步初始化方法(推荐)

构造函数只做同步初始化,把异步查询放到专门的init方法里,用async/await处理:

private teste1: any
private teste2: any

constructor(protected ctx: HttpContextContract) {}

// 异步初始化方法
async init() {
  // 等待数据库查询完成后赋值
  this.teste1 = await Database.from('estoquepas')
  this.teste2 = await Estoquepas.findBy('siagreId', this.IDSiagre.siagreId)
  
  console.log(this.teste1)
  console.log(this.teste2)
}

使用类的时候,先调用init并等待完成:

const yourInstance = new YourClassName(ctx)
await yourInstance.init()

// 之后就可以安全使用teste1和teste2了

方法二:构造函数内用异步立即执行函数

如果一定要在构造函数里处理,用async立即执行函数包裹异步逻辑,但要注意:构造函数执行完后,变量可能还没就绪,后续使用需要等待初始化完成:

private teste1: any
private teste2: any
// 用一个Promise标记初始化完成状态
private ready: Promise<void>

constructor(protected ctx: HttpContextContract) {
  this.ready = (async () => {
    this.teste1 = await Database.from('estoquepas')
    this.teste2 = await Estoquepas.findBy('siagreId', this.IDSiagre.siagreId)
    
    console.log(this.teste1)
    console.log(this.teste2)
  })()
}

// 后续需要使用变量的方法,先等待ready完成
async doBusinessLogic() {
  await this.ready
  // 这里可以安全访问this.teste1和this.teste2
}
注意事项
  • 不要把构造函数声明为async,因为async构造函数返回的是Promise,而不是类实例,会破坏类的正常使用。
  • 优先用方法一,把异步逻辑和构造函数分离,代码更清晰,也能避免实例未初始化就被使用的问题。

内容的提问来源于stack exchange,提问作者marcelo.delta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:05:39