# How to manage firebase async data fetching?

**URL:** <https://forums.swift.org/t/how-to-manage-firebase-async-data-fetching/47978>\
**Category:** Using Swift\
**Tags:** off-topic\
**Created:** [May 8, 2021, 1:17pm UTC](https://forums.swift.org/t/how-to-manage-firebase-async-data-fetching/47978 "2021-05-08T13:17:04Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![erdemeylul](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/erdemeylul/32/16902_2.png) [@erdemeylul](https://forums.swift.org/u/erdemeylul)\
**Post date:** [May 8, 2021, 1:17pm UTC](https://forums.swift.org/t/how-to-manage-firebase-async-data-fetching/47978/1 "2021-05-08T13:17:04Z")

</div>

In the code below, "count" variable always returns 0 because the data is not fetched from the database yet. How can i write the same function again to make sure that the variable is assigned a value?

func getUnreadMessages(name: String) -\> Int{  
guard let uid = AuthViewModel.shared.userSession?.uid else {return 0}

```
    var count = Int()
    
    Firestore.firestore().collection("users").document(uid).collection("chats").document(name).collection("messages").whereField("read", isEqualTo: false).getDocuments { (snapshot, _) in
        guard let documents = snapshot?.documents.compactMap({ $0.documentID }) else {return}
        
        count = documents.count
    }
    
    return count
}

```
