admin管理员组文章数量:1134246
I have read that toPromise()
is being deprecated in RxJS 7 and will be removed in RxJS 8.
I have often used it with async await syntax in angular to handle http calls. Is it considered an anti pattern?
I understand the concept of streams but an http call only emit a single value. I don't get the point of observable for a simple http call. What should I use next? should I fully embrace reactive programming?
I have read that toPromise()
is being deprecated in RxJS 7 and will be removed in RxJS 8.
I have often used it with async await syntax in angular to handle http calls. Is it considered an anti pattern?
I understand the concept of streams but an http call only emit a single value. I don't get the point of observable for a simple http call. What should I use next? should I fully embrace reactive programming?
- 2 As is conventional, the alternatives are provided in the deprecation: github.com/ReactiveX/rxjs/commit/… – jonrsharpe Commented Apr 11, 2021 at 11:23
5 Answers
Reset to default 158Why is this happening?
As mentioned here, these are the main reasons why toPromise
is being deprecated:
One goal was to remove it from the
Observable
prototype and turn it into a standalone util function.The naming of
toPromise
is not the best. Especially when used in combination withawait
it does not read very well:await categories$.toPromise()
vsawait lastValueFrom(categories$)
The type information of
toPromise
is wrong. When the sourceObservable
completed without ever emitting a single value - it resolved withundefined
. It should reject in that case. APromise
is a "promise" that when it resolves a value will be there - and be itundefined
. But when the stream completes without ever emitting a value you can't differentiate between a stream that a emittedundefined
on purpose and a stream that completed without ever emitting anymore
What should you use next?
If you really insist doing it the promise way, lastValueFrom
/firstValueFrom
. Otherwise switching to reactive programming would be the way to go.
Using toPromise
( deprecated ) -
public async loadCategories() {
this.categories = await this.inventoryService
.getCategories()
.toPromise()
}
Using lastValueFrom
( new ) -
import { lastValueFrom } from 'rxjs';
public async loadCategories() {
const categories$ = this.inventoryService.getCategories();
this.categories = await lastValueFrom(categories$);
}
This link should help -
https://indepth.dev/posts/1287/rxjs-heads-up-topromise-is-being-deprecated
firstValueFrom
and lastValueFrom
is definitly a better alternative for many reasons:
- The naming is more readable and self explanatory.
- The additional ability to select either first or last value.
- The additional ability to declare a default value in case the observable didn't emit any value at all like so
await lastValueFrom(data$, {defaultValue: 'Some default value'})
For more about this checkout the video below:
https://www.youtube.com/watch?v=3aeK5SfWBSU
Code example:
Deprecated use:
await this.http.post<boolean>(`/someApi`).toPromise()
.then((value) => {
console.log(`Result: ` + value);
})
New code:
import { firstValueFrom } from 'rxjs';
await firstValueFrom(this.http.post<boolean>(`/someApi`))
.then((value) => {
console.log(`Result: ` + value);
})
For the most stubborn, I've found this workaround to keep toPromise() forever. Put this in your main.ts or similar (the file that gets to boostrap the entire application):
declare module "rxjs" {
interface Observable<T> {
/**
* Extension method. Applies 'lastValueFrom' to Observable<T>.
*/
toPromise(): Promise<T | undefined>;
}
}
Observable.prototype.toPromise = function <T>(this: Observable<T>): Promise<T> {
return lastValueFrom(this);
};
The first part declares the new typing for toPromise, and the second bit actually implements it. This works already while toPromise hasn't been yet removed, and will continue working going forward.
The following code is what I personally used:
// From my Component
const apiResponse = await lastValueFrom(this.postSomethingAPI(somethingId, somethingElseId));
// From my Service
postSomethingAPI = (somethingId: string, somethingElseId: string) => {
const queryParams = `someParameter`;
const packagedData = {
somethingId: somethingId,
somethingElseId: somethingElseId,
};
return this.http.post<any>(BACKEND_URL + queryParams, packagedData);
};
本文标签: javascriptRxjs toPromise() deprecatedStack Overflow
版权声明:本文标题:javascript - Rxjs toPromise() deprecated - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736849795a1955453.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论