Since a 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);
});
另请参阅有关获取实时更新的 Firestore 文档 https://firebase.google.com/docs/firestore/query-data/listen
To tell get()
要从缓存返回数据,请执行以下操作:
db.collection("cities").where("capital", "==", true)
.get({ source: 'cache' })
.then(function(querySnapshot) {
...
但请注意,这意味着您永远不会从服务器获得更新的值。