How to manage firebase async data fetching?

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
Terms of Service

Privacy Policy

Cookie Policy