How can I use Async/Await on HttpService
using NestJs?
The below code doesn`t works:
JavaScript
x
4
1
async create(data) {
2
return await this.httpService.post(url, data);
3
}
4
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
1
5
1
create(data): Promise<AxiosResponse> {
2
return this.httpService.post(url, data).toPromise();
3
^^^^^^^^^^^^^
4
}
5
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
1
6
1
import { firstValueFrom } from 'rxjs';
2
3
// ...
4
5
return firstValueFrom(this.httpService.post(url, data))
6