NestJS – 为什么方法在执行代码之前返回

huangapple go评论64阅读模式
英文:

NestJS - Why Does Method Return Before Executing Code

问题

我对Node和Nest JS非常陌生,遇到了一个看起来很简单的问题,但我解决不了。基本上,我有一个包装数据库调用的服务类,以及一个调用服务方法的控制器方法。问题是该方法在执行数据库调用之前就返回了。以下是控制器:

@Get(':mapCountry')
async getProductsByMapCountry(
  @Param() params: { customerId: string, mapCountry: string },
  @Query() query: QueryArgs
): Promise<any> {
  const customerId = params.customerId
  const mapCountry = params.mapCountry
  const args = getArgs(query)
  const limit = args.paginate
  const offset = args.page
  return this.productsService.getProductsByMapCountry(customerId, mapCountry, limit, offset)
}

以下是服务方法:

async getProductsByMapCountry(customerId: string, mapCountry: string, limit: number, offset: number): Promise<any>{
    var products: any
    await this.pool.connect();
    const request = this.pool.request()
      .input('CustomerId', customerId)
      .input('MapCountry', mapCountry)
      .input('Limit', limit)
      .input('Offset', offset)
      .execute(`[dbo].[GetProductsByMapCountry]`, (err, result) => {
        const paging = result.recordsets[1][0] as paging;
        products = { 
          docs: result.recordsets[0],
          pages: paging.pages,
          total: paging.total,
          limit: limit,
          offset: offset
      };
      console.log(products);
    });
    return products;
  }

所有与数据库交互的逻辑在该方法返回之后才触发。我知道这一定很简单,但我就是找不到解决办法。任何帮助将不胜感激。
英文:

I am very new to node and nest JS, and am having what has to be a very simple problem, but I can't figure it out. Basically, I have a service class wrapping DB calls, and a controller method that calls a service method. The problem is the method returns before executing the DB call. Here's the controller:

    @Get(&#39;:mapCountry&#39;)
  async getProductsByMapCountry(
    @Param() params: { customerId: string, mapCountry: string },
    @Query() query: QueryArgs
  ): Promise&lt;any&gt; {
    const customerId = params.customerId
    const mapCountry = params.mapCountry
    const args = getArgs(query)
    const limit = args.paginate
    const offset = args.page
    return this.productsService.getProductsByMapCountry(customerId, mapCountry, limit, offset)
  }

and here's the service method

async getProductsByMapCountry(customerId: string, mapCountry: string, limit: number, offset: number): Promise&lt;any&gt;{
    var products: any
    await this.pool.connect();
    const request = this.pool.request()
      .input(&#39;CustomerId&#39;, customerId)
      .input(&#39;MapCountry&#39;, mapCountry)
      .input(&#39;Limit&#39;, limit)
      .input(&#39;Offset&#39;, offset)
      .execute(`[dbo].[GetProductsByMapCountry]`, (err, result) =&gt; {
        const paging = result.recordsets[1][0] as paging;
        products = { 
          docs: result.recordsets[0],
          pages: paging.pages,
          total: paging.total,
          limit: limit,
          offset: offset
      };
      console.log(products);
    });
    return products;
  }

All the logic that hits the DB fires after the method returns. I know this has to be simple, but I just can't find the fix. Any help would be appreciated.

答案1

得分: 1

你的 getProductsByMapCountry 函数返回一个 promise,并且你希望它以产品结果解析。如果你的 execute 函数返回一个 promise,你可以等待它,这样就可以将这两个 promise 链接在一起。

但是 execute 接受一个回调函数,它在完成时调用。该回调与你尝试返回的 promise 没有关联。因此,你需要将它们连接起来。你可以通过将 execute 调用包装在一个新的 promise 中来实现这一点,该 promise 在调用回调时解析或拒绝。

英文:

Your getProductsByMapCountry function returns a promise, and you want it to resolve with the products result. If your execute function returned a promise, you could await it, and this would chain the two promises together.

But execute takes a callback function instead, which it calls when it's done. That callback has no connection to the promise that you're trying to return. So you need to connect them. You can do this by wrapping the execute call in a new promise, which resolves or rejects when the callback is called.

async getProductsByMapCountry(customerId: string, mapCountry: string, limit: number, offset: number): Promise&lt;any&gt;{
    await this.pool.connect();
    return new Promise((resolve, reject) =&gt; {
        this.pool.request()
            .input(&#39;CustomerId&#39;, customerId)
            .input(&#39;MapCountry&#39;, mapCountry)
            .input(&#39;Limit&#39;, limit)
            .input(&#39;Offset&#39;, offset)
            .execute(`[dbo].[GetProductsByMapCountry]`, (err, result) =&gt; {
                if (err) {
                    reject(err);
                    return;
                }
                const paging = result.recordsets[1][0] as paging;
                resolve({
                    docs: result.recordsets[0],
                    pages: paging.pages,
                    total: paging.total,
                    limit: limit,
                    offset: offset
                });
            });
    });
}

答案2

得分: 0

尝试将 await 添加到此函数中:

    @Get('mapCountry')
      async getProductsByMapCountry(
        @Param() params: { customerId: string, mapCountry: string },
        @Query() query: QueryArgs
      ): Promise<any> {
        const customerId = params.customerId
        const mapCountry = params.mapCountry
        const args = getArgs(query)
        const limit = args.paginate
        const offset = args.page
        return await this.productsService.getProductsByMapCountry(customerId, mapCountry, limit, offset)
      }
英文:

Try to add await to your function here:

@Get(&#39;:mapCountry&#39;)
  async getProductsByMapCountry(
    @Param() params: { customerId: string, mapCountry: string },
    @Query() query: QueryArgs
  ): Promise&lt;any&gt; {
    const customerId = params.customerId
    const mapCountry = params.mapCountry
    const args = getArgs(query)
    const limit = args.paginate
    const offset = args.page
    return await this.productsService.getProductsByMapCountry(customerId, mapCountry, limit, offset)
  }

huangapple
  • 本文由 发表于 2023年5月21日 02:34:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76296812.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定