Firestore realtime listener to multiple documents async await

随声附和 提交于 2021-01-28 07:21:05

问题


I am wondering if the realtime listener for Firestore supports async await instead of promise?

The documentation suggests:

var unsubscribe = db.collection("cities").where("state", "==", "CA").onSnapshot(function(querySnapshot) {
    var cities = [];
    querySnapshot.forEach(function(doc) {
       cities.push(doc.data().name);
    });
    console.log("Current cities in CA: ", cities.join(", "));
});
unsubscribe();

Could I write the above realtime listener using async await? I tried the following and the listener does not work anymore. Also, it won't be possible to detach the listener anymore.

var querySnapshot = db.collection("cities").where("state", "==", "CA").onSnapshot
var cities = [];
querySnapshot.forEach(function(doc) {
   cities.push(doc.data().name);
});
console.log("Current cities in CA: ", cities.join(", "));

How could I write it using async await and would be able to use the detacher as well?


回答1:


async/await (used with promises) doesn't make sense to use with listeners. A promise represents a unit of work that finishes with a final value, or an error. A listener is an ongoing process that doesn't finish until the listener is removed using the unsubscribe function. They are fundamentally different things.

If you want to do a one-time query that gives you a promise that you can await, you should use get() instead of onSnapshot() as described in the documentation. Only use a listener if you want updates to a query as the results change over time.



来源:https://stackoverflow.com/questions/63350415/firestore-realtime-listener-to-multiple-documents-async-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!