[英]Cache first implementation for get in firestore
我希望firestore每次都首先從緩存中獲取數據。 根據Firestore文檔,傳遞“緩存”或“服務器”選項必須啟用相同選項。 下面的例子
db.collection("cities").where("capital", "==", true)
.get("cache")
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
但是,無論我設置“緩存”還是“服務器”,查詢似乎都首先嘗試網絡,然后再嘗試緩存。
由於get()
僅獲取一次您的值,因此它將始終檢查服務器中數據的最新值。 如果這是您應用中的第一個Firestore操作,則可能需要它建立與數據庫的網絡連接,這可能需要一些時間。
如果您很快想從緩存中獲取數據,然后稍后從服務器獲取修改,請使用onSnapshot
:
db.collection("cities").where("capital", "==", true)
.onSnapshot(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
要告訴get()
從緩存中返回數據,請執行以下操作:
db.collection("cities").where("capital", "==", true)
.get({ source: 'cache' })
.then(function(querySnapshot) {
...
但是請注意,這意味着您將永遠不會從服務器獲取更新的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.