首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用允诺/异步在函数返回中可观察到?

如何使用允诺/异步在函数返回中可观察到?
EN

Stack Overflow用户
提问于 2021-10-19 10:33:22
回答 1查看 673关注 0票数 1

我正在使用nestjs,并希望编写一个带有缓存的返回Observable (rxjs)的函数。

代码语言:javascript
复制
import { HttpService } from '@nestjs/axios';
import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';
import { Cache } from 'cache-manager';
import { map, of, Observable } from 'rxjs';

interface User {
  id: string;
  // ...
}

@Injectable()
export class Service {
  constructor(
    @Inject(CACHE_MANAGER) protected cache: Cache,
    protected readonly httpService: HttpService,
  ) {}
  fetchUser = (id: string): Observable<User> {
    const url = 'xxx';
    const user: string = this.cache.get(`user:${id}`); // but here is `Promise<string>` actually
    if (user) {
      return of(JSON.parse(user) as User);
    }

    return this.httpService.get<User>(url).pipe(
      map(({ data }) => {
        this.cache.set(`user:${id}`, JSON.stringify(data));
        return data;
      })
    );
  }
}

逻辑非常简单,如果存在缓存,则返回缓存,否则调用api,保存到缓存,并返回结果。唯一的问题是缓存将返回一个承诺。怎样才能做到这一点?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-19 10:38:27

您可以使用RxJS from函数将承诺转换为可观察的承诺。在那里,您可以使用switchMap操作符+ of函数返回从缓存中获取的用户或进行HTTP调用。

代码语言:javascript
复制
fetchUser(id: string): Observable<User> {
  const url = 'xxx';

  const user$ = this.httpService.get<User>(url).pipe(
    map(({ data }) => {
      this.cache.set(`user:${id}`, JSON.stringify(data));
      return data;
    })
  );

  return from(this.cache.get(`user:${id}`)).pipe(
    switchMap((user: string) => 
      !!user ? of(user) : user$
    )
  );
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69629266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档