NestJs 异步 httpService 调用 [英] NestJs async httpService call

查看:1066
本文介绍了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 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆