本文介绍了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 调用
发布评论