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

NestJS问题:为何方法在执行数据库代码前提前返回?

问题解决方法

问题根源在于你使用了execute的回调函数版本,await仅等待了pool.connect()完成,但数据库查询的异步操作没有被await捕获,导致方法直接返回了未赋值的products变量,回调逻辑在返回后才执行。

修复后的服务方法代码

改用execute的Promise版本(不传回调时会返回Promise),用await等待查询完成后再处理结果:

async getProductsByMapCountry(customerId: string, mapCountry: string, limit: number, offset: number): Promise<any>{
    // 获取连接并确保后续释放
    const connection = await this.pool.connect();
    try {
      // 等待数据库查询执行完成
      const result = await connection.request()
        .input('CustomerId', customerId)
        .input('MapCountry', mapCountry)
        .input('Limit', limit)
        .input('Offset', offset)
        .execute(`[dbo].[GetProductsByMapCountry]`);
      
      // 组装返回数据
      const paging = result.recordsets[1][0] as paging;
      const products = { 
        docs: result.recordsets[0],
        pages: paging.pages,
        total: paging.total,
        limit: limit,
        offset: offset
      };
      console.log(products);
      return products;
    } finally {
      // 无论是否出错,都释放数据库连接
      connection.release();
    }
}

关键说明

  • 去掉execute的回调参数,使用Promise风格调用,让await能正确等待数据库操作完成
  • 添加try/finally块确保数据库连接被释放,避免连接泄漏
  • 现在方法会在数据库查询完成、组装好返回值后才返回,不会再提前返回未定义的products

内容的提问来源于stack exchange,提问作者LandonC

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 05:00:21