Andre Baltieri
Andre Baltieri

Reputation: 435

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

Upvotes: 26

Views: 54762

Answers (6)

Kim Kern
Kim Kern

Reputation: 60357

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:

import { firstValueFrom } from 'rxjs';

// ...

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

Upvotes: 60

Vinay Kaithwas
Vinay Kaithwas

Reputation: 1513

try these below one instead of only async-await.

There are some basic reasons behind the deprecation of toPromise.

We know that Promise and Observables that both collections may produce values over time. where Observables return none or more and Promise return only one value when resolve successfully.

there is a main reason behind the seen

Now we have 2 new functions.

Upvotes: 2

Guster
Guster

Reputation: 1821

As toPromise() is being deprecated, you can replace it with firstValueFrom or lastValueFrom

For example:

const resp = await firstValueFrom(this.http.post(`http://localhost:3000/myApi`)

https://rxjs.dev/deprecations/to-promise

Upvotes: 29

Ben Hason
Ben Hason

Reputation: 11

You can just add the .toPromise() at the end of each method call but then you lose the power of observables, like it’s ability to add retry to failed http call by just adding the retry operator.

You can implement this abilities by yourself and create your own module or just use package that already implemented it like this : https://www.npmjs.com/package/nestjs-http-promise

Upvotes: 1

Hassan Ali Shahzad
Hassan Ali Shahzad

Reputation: 2724

Following is complete example for working code:

.toPromise() is actually missing

async getAuthToken() {
    const payload = {
      "SCOPE": this.configService.get<string>('SCOPE'),
      "EMAIL_ID": this.configService.get<string>('EMAIL_ID'),
      "PASSWORD": this.configService.get<string>('PASSWORD'),
    };
    const url = this.configService.get<string>('AUTHTOKEN_URL')
    const response = await this.httpService.post(
      url,
      payload
    ).toPromise();
    console.log(response.data);
    return response.data;
  }

Upvotes: 1

Mahdi Imani
Mahdi Imani

Reputation: 204

rxjs library is most powerful concurrency package that chosen form handling system event like click, external request like get data or delete record and ....

The main concept behind this library is:

handle data that receive in future

therefor you most use 3 argument in observable object like

observablSource.subscribe(
   data => { ... },
   failure => { ... },
   compelete => { ... }
)

but for most backend developer use Promises that comes from ECMAScript 6 feature and is native part of JavaScript.

By default in Angular 4+ and Nest.js use rxjs that support Observable. In technical details you can find a solution for change automatic observable to promise.

const data: Observable<any>;
data.from([
   {
      id: 1,
      name: 'mahdi'
   }, 
   {
      id: 2,
      name: 'reza'
   },
 ])

now you have simulate a request with observable type from server. if you want to convert it to Pormise use chained method like example:

   data.toPromise();

from this step you have promised object and form using it better to attach async/await

 async userList( URL: string | URLPattern ) {
    const userList = await this.http.get<any>( URL ).toPromise();
    ...
 }

Upvotes: 8

Related Questions