Skip to content
Advertisement

NestJs async httpService call

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);
}

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.

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

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

8 People found this is helpful
Advertisement