问题
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