1

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, I see. In that case, I cannot use async await with real-time listeners. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.