Skip to content
Advertisement

NestJs async httpService call

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

JavaScript

Advertisement

Answer

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

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.

JavaScript

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

Update 2022

toPromise is deprecated. Instead, you can use firstValueFrom:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement