[英]How to handle for promise inside a piped map
我肯定我在這里很困惑,所以請提供任何幫助。
這是我的場景:
我從 Firestore 中提取了一個文檔:
return this.afs.collection("events").doc(eventID).snapshotChanges().pipe(
map( document => {
})
);
到這里為止一切都很好。
但在地圖內我需要一個承諾來解決(或不解決)
例如:
return this.afs.collection("events").doc(eventID).snapshotChanges().pipe(
map( document => {
// This is a promise the below part
const data = await EventImporterJSON.getFromJSON(document.payload.data())
return data
})
);
我知道await
不能在那里發生。 我很困惑如何解決這個問題,也許我在 observables 和 rxjs 上工作的時間不夠長。
最后我想要實現的是:
獲取文檔。 映射並處理它,但在這個過程中,我需要處理一個承諾。
不過,我不想將該承諾返回給調用者。
這有意義嗎?
還是我的結構完全錯誤?
這是mergeMap
或concatMap
的典型用例:
return this.afs.collection("events").doc(eventID).snapshotChanges().pipe(
mergeMap(document => {
// This is a promise the below part
return EventImporterJSON.getFromJSON(document.payload.data())
})
);
但是,您也可以使用async - await
因為諸如mergeMap
類的運算符以相同的方式處理 Observables、Promises、數組等,因此您只需在mergeMap
的項目函數中返回一個 Promise 就可以正常工作。
通常,您不需要在單個方法中使用多個await
,因為更“Rx”的做事方式是鏈接運算符,但如果您願意,您可以因為async
方法返回一個 Promise 並且 RxJS 會像處理它一樣任何其他承諾。
const delayedPromise = () => new Promise(resolve => {
setTimeout(() => resolve(), 1000);
})
of('a').pipe(
mergeMap(async v => {
console.log(1);
await delayedPromise();
console.log(2);
await delayedPromise();
console.log(3);
await delayedPromise();
return v;
})
).subscribe(console.log);
// 1
// 2
// 3
// a
Live demo: https://stackblitz.com/edit/rxjs-3fujcs
Observables 可以看作是 Promise 的一層,你為什么不這樣使用你的 Promise 呢? 像這樣 :
let getDataFromJson(payloadData){
return from(EventImporterJSON.getFromJSON(payloadData());
}
return this.afs.collection("events").doc(eventID).snapshotChanges().pipe(
map(document=>document.payload.data),
switchMap( payloadData=> getDataFromJson(payloadData)))
.subscribe(result=>{
//final result
});
1 用 map 管道你的第一個 observable 只是為了簡化你的返回值
2 switchMap 到另一個可觀察對象,這將是您作為可觀察對象的承諾(使用“來自”運算符);
map 運算符用於以同步和“純”方式改進結果,例如僅返回對象的少數屬性或過濾數據,在這里您想要鏈接兩個異步操作,因此我建議您將其保留在 rx 方法中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.