[英]What should I use instead of document.queryselector() when using React?
[英]What should I use instead of toPromise() when using await on an Observable?
這個頁面說"toPromise has been deprecated. (RxJS 5.5+)"
但我最近一直在使用它和 AngularFire2(當我只想要一個結果時),如下所示:
const foo = await this.afs.doc(`docPath`).valueChanges().toPromise();
我不應該這樣做嗎? 如果不是,那么await
替代方案是什么?
更新:
在下面的答案之后,我改變了這個:
const foo = await this.afs.doc(`docPath`).valueChanges().toPromise();
...對此:
const foo = await (new Promise(resolve => this.afs.doc(`docPath`).valueChanges().pipe(first()).subscribe(result => resolve(result))));
有人可以向我解釋一下這是如何改進的嗎? 對我來說似乎是一個倒退。
你應該放管后!
.pipe(take(1)).toPromise
對於那些想要瘋狂的人來說,還有其他一些選擇:
const foo = await this.afs.doc(`docPath`).valueChanges().pipe(take(1)).toPromise();
或者
const foo = (await this.afs.doc('docPath').get().toPromise()).data();
或者
const foo = (await this.afs.doc('docPath').get().pipe(take(1)).toPromise()).data();
或者
const foo = (await this.afs.doc('docPath').snapshotChanges().pipe(take(1))
.toPromise()).payload.data();
但最短的是:
const foo = (await this.afs.doc('docPath').ref.get()).data();
在任何可以使用take(1)
的地方,如果你想發出錯誤,你可以使用first()
。
有關 Firebase 的更多承諾,請參見此處。
Ĵ
firstValueFrom
和lastValueFrom
是更好的選擇,原因有很多:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.