NestJs 异步 httpService 调用

编程入门 行业动态 更新时间:2024-10-27 03:42:20
本文介绍了NestJs 异步 httpService 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何使用 NestJs 在 HttpService 上使用 Async/Await?下面的代码不起作用:

How can I use Async/Await on HttpService using NestJs? The below code doesn`t works:

async create(data) { return await this.httpService.post(url, data); }

推荐答案

HttpModule 使用 Observable 而不是 Promise异步/等待.所有 HttpService 方法都返回 Observable>.

The HttpModule uses Observable not Promise which doesn't work with async/await. All HttpService methods return Observable<AxiosResponse<T>>.

因此,您可以将其转换为 Promise,然后在调用它时使用 await,或者只返回 Observable 并让调用者处理它.

So you can either transform it to a Promise and then use await when calling it or just return the Observable and let the caller handle it.

create(data): Promise<AxiosResponse> { return this.httpService.post(url, data).toPromise(); ^^^^^^^^^^^^^ }

请注意,return await 几乎(除了 try catch)总是多余的.

Note that return await is almost (with the exception of try catch) always redundant.

更多推荐

NestJs 异步 httpService 调用

本文发布于:2023-11-25 04:19:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628296.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NestJs   httpService

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!