简体   繁体   中英

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

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

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

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM