Reputation: 2656
I have a question about the use of rxjs firstValueFrom function.
Somehwere (in code I had to take over) I see the following constuction: (This is NodeJS/NestJS code)
import { firstValueFrom } from 'rxjs';
...
async getAllProjects() {
const res = await firstValueFrom(
this.httpService.get(
'https://endpoint.somerestservice.com',
{
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'XXX',
},
},
),
);
}
And I don't understand what the added value is of firstValueFrom in this.
Why not doing it like this and leave out the rxjs-firstValueFrom?
async getAllProjects() {
const res = await this.httpService.get(
'https://endpoint.somerestservice.com',
{
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'XXX',
},
},
);
}
And yes, I have read the docs on firstValueFrom. As I understand it's making an Observable-Stream of the Promise. Why would you want to do that?
Upvotes: 2
Views: 4764
Reputation: 529
await
-ing an Observable<dto>
will resolve immediately, causing:
res
to be an Observable<dto>
instead of the dto
itself that is returned from the backend call,With that you either achieve "fire & forget" approach or a possible "pyramid of doom" if you have long subscribe/callback code.
On the other hand await
-ing the Promise<dto>
(returned by firstValueFrom
) will suspend the execution until the backend call completes, then assigns res
, then continues the execution in the next line of code.
Upvotes: 1
Reputation: 70412
Generally it comes down to a matter of opinion and comfort with RxJS. By using firstValueFrom
or lastValueFrom
the Observable is turned into a Promise that can be await
ed, which is usually a more familiar API for most devs. Nest will automatically handle if you return an Observable or a Promise, so it makes no difference there. If you're comfortable with the RxJS pipeline and how to mutate and handle Observables you can keep using .pipe()
and the rxjs operators, otherwise, using firstValeuFrom
or lastValueFrom
could be more beneficial just so it works as usual promises do. It really just depends on what you're comfortable with
Upvotes: 4