Nestjs Async Httpservice Call
Solution 1:
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> {
returnthis.httpService.post(url, data).toPromise();
^^^^^^^^^^^^^
}
Note that return await
is almost (with the exception of try catch) always redundant.
Solution 2:
As toPromise()
is being deprecated, you can replace it with firstValueFrom
or lastValueFrom
For example:
const resp = awaitfirstValueFrom(this.http.post(`http://localhost:3000/myApi`)
Solution 3:
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
asyncuserList( URL: string | URLPattern ) {
const userList = awaitthis.http.get<any>( URL ).toPromise();
...
}
Solution 4:
Following is complete example for working code:
.toPromise() is actually missing
asyncgetAuthToken() {
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 = awaitthis.httpService.post(
url,
payload
).toPromise();
console.log(response.data);
return response.data;
}
Solution 5:
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
Post a Comment for "Nestjs Async Httpservice Call"