繁体   English   中英

当我使用 Firestore 监听 function 时,我是否必须使用 async/await?

[英]Do I have to use async/await when i use Firestore listen function?

我有以下听 function

 FirebaseFirestore.instance.collection('users').doc(widget.userId).snapshots().listen((event) 
    async{
     if(!event.metadata.isFromCache){
     String myFirstValue = await event.get('name');
     

    // here i have many local operations that depends on `myFirstValue` Constantly as the 
      document changes

     }
    
     });

在前面的代码中,经过多次测试,我注意到我可以使用await并且我不能像下面这样使用它

String myFirstValue = event.get('name');

在所有情况下,我都能得到正确的结果。

我完全糊涂了。 我应该使用await还是不使用? 有什么更好的用途? 如果我不使用等待,是否有某些情况会导致我的操作出现错误,这取决于我的myFirstValue

换句话说:来自.listen((event) event事件是否将具有所有值并且不需要在myFirstValue中使用 await ?

您代码中的eventDocumentSnapshot 如果我们查看参考文档DocumentSnapshot.get没有返回Future ,那么调用它时就不需要使用await了。

这与DocumentReference.get()不同,它确实返回了Future 在此处使用await将打开Future并为您提供底层DocumentSnapshot

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM