RXJS 和 Nestjs 返回值的问题

发布于 2025-01-11 08:06:32 字数 1159 浏览 0 评论 0原文

我从端点获取一些 JSON(为此我使用 @nestjs/axios)。问题在于响应是一个 Observable。返回值时这会使事情变得复杂。我似乎无法让 async/await 工作,我真的没有主意了...

这是我的终点:

async getBalance({ address, network }: WalletDto): Promise<any> {
    let nativeBalance: string

    try {
      this.httpService
        .get<{ balance: string }>(
          `https://deep-index.moralis.io/api/v2/${address}/balance?chain=${network}`,
          {
            headers: {
              Accept: 'application/json',
              'X-Api-Key': 'lol',
            },
          },
        )
        .subscribe({
          next: ({ data }) => {
            nativeBalance = utils.formatEther(data.balance)
          },
          complete: () => {
            const chain = supportedChains.find(
              ({ name }) => name.toLowerCase() === network,
            )

            return {
              chain,
              nativeBalance,
            }
          },
        })
    } catch (error) {
      // TODO handle error
    }
  }

我已经搞乱了 .pipe() 但不明白什么它的作用或工作原理...顺便说一句,supportedChains 是一个静态数组,不是获取的一部分。

I'm getting some JSON from an endpoint (I'm using @nestjs/axios for this). The issue is that the response is an Observable. This complicates things when returning values. I can't seem to get async/await to work, I'm truly out of ideas...

Here's my endpoint:

async getBalance({ address, network }: WalletDto): Promise<any> {
    let nativeBalance: string

    try {
      this.httpService
        .get<{ balance: string }>(
          `https://deep-index.moralis.io/api/v2/${address}/balance?chain=${network}`,
          {
            headers: {
              Accept: 'application/json',
              'X-Api-Key': 'lol',
            },
          },
        )
        .subscribe({
          next: ({ data }) => {
            nativeBalance = utils.formatEther(data.balance)
          },
          complete: () => {
            const chain = supportedChains.find(
              ({ name }) => name.toLowerCase() === network,
            )

            return {
              chain,
              nativeBalance,
            }
          },
        })
    } catch (error) {
      // TODO handle error
    }
  }

I've messed around with .pipe() but don't understand what it does or how it works... Btw, supportedChains is a static array, not part of the fetch.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

魂ガ小子 2025-01-18 08:06:32

作为可观察对象的超级简短介绍:如果 Promise 是一个仅代表一个最终值的对象,那么可观察对象就是一个代表任意数量最终值流的对象。 Observables 附带了一组用于操作值流的运算符函数(您提到的管道函数用于传递您想要应用的任何运算符)。

如果您只想从可观察量转换为承诺,那么您可以使用可观察量的 .toPromise 属性来实现。如果您使用的是 rxjs 版本 7,则 toPromise 已弃用,您可以使用 firstValueFromlastValueFrom

import { firstValueFrom } 'rxjs';
//...
async getBalance({ address, network }: WalletDto): Promise<any> {
  try {
    const observable = this.httpService.get<{ balance: string }>(
      `https://deep-index.moralis.io/api/v2/${address}/balance?chain=${network}`,
      {
        headers: {
          Accept: "application/json",
          "X-Api-Key": "lol",
        },
      }
    );

    const { data } = await observable.toPromise();
    // OR in rxjs v7:
    // const { data } = await firstValueFrom(observable)

    const nativeBalance = utils.formatEther(data.balance);

    const chain = supportedChains.find(
      ({ name }) => name.toLowerCase() === network
    );

    return {
      chain,
      nativeBalance,
    };
  } catch (err) {}
}

As a super brief intro to observables: if a Promise is an object that represents exactly one eventual value, then an Observable is an object that represents a stream of any number of eventual values. Observables come with a collection of operator functions for manipulating the stream of values (that pipe function you mentioned is used to pass in any operators you want to apply).

If you just want to convert from observables to promises, then you can do so with the .toPromise property on observables. If you're using rxjs version 7 then toPromise is deprecated and instead you can use firstValueFrom or lastValueFrom.

import { firstValueFrom } 'rxjs';
//...
async getBalance({ address, network }: WalletDto): Promise<any> {
  try {
    const observable = this.httpService.get<{ balance: string }>(
      `https://deep-index.moralis.io/api/v2/${address}/balance?chain=${network}`,
      {
        headers: {
          Accept: "application/json",
          "X-Api-Key": "lol",
        },
      }
    );

    const { data } = await observable.toPromise();
    // OR in rxjs v7:
    // const { data } = await firstValueFrom(observable)

    const nativeBalance = utils.formatEther(data.balance);

    const chain = supportedChains.find(
      ({ name }) => name.toLowerCase() === network
    );

    return {
      chain,
      nativeBalance,
    };
  } catch (err) {}
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文