NestJs async httpService call
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();
...
}
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
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
- Official: https://rxjs.dev/deprecations/to-promise
- Stack:Rxjs toPromise() deprecated
Now we have 2 new functions.
lastValueFrom : last value that has arrived when the Observable completes for more https://rxjs.dev/api/index/function/firstValueFrom
firstValueFrom: you might want to take the first value as it arrives without waiting an Observable to complete for more https://rxjs.dev/api/index/function/lastValueFrom
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))