[SOLVED] NestJs async httpService call

Table of Contents

Issue

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

Solution

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.

Update 2022

toPromise is deprecated. Instead, you can use firstValueFrom:

return firstValueFrom(this.httpService.post(url, data))

Answered By – Kim Kern

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *