Firestore实时监听多个文档的实时监听器 [英] Firestore realtime listener to multiple documents async await

查看:45
本文介绍了Firestore实时监听多个文档的实时监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Firestore的实时侦听器是否支持 async await 而不是promise?

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

文档建议:

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();

我可以使用 async await 编写上述实时侦听器吗?我尝试了以下操作,但侦听器不再起作用.另外,将无法再分离侦听器.

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(", "));

我如何使用 async await 编写它,并且还可以使用分离器?

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

推荐答案

async/await(与promises一起使用)与侦听器一起使用是没有意义的.承诺表示以最终值或错误结尾的工作单元.侦听器是一个持续的过程,直到使用取消订阅功能将其删除后,该过程才会结束.它们是根本不同的东西.

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.

如果您要进行一次查询以保证可以等待,则应使用 get()代替如上所述的 onSnapshot()文档中.当结果随时间变化时,如果要更新查询,请仅使用侦听器.

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.

这篇关于Firestore实时监听多个文档的实时监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆