Home > database >  How to make this function wait for the database response then return a value
How to make this function wait for the database response then return a value

Time:10-13

func getUserChatRoom(chatroomsID: [String], handler: @escaping(_ chatrooms: [ChatRoomModel])  -> ()) {
    guard !chatroomsID.isEmpty else {
        return handler([])
    }
    print("1")
    let group = DispatchGroup()
    
    var chatrooms: [ChatRoomModel] = []
    
    for id in chatroomsID {
        print("2")

        group.enter()
        print("3")

        db.collection("chatrooms").document(id).getDocument { (document, error) in
            if let doc = document, doc.exists,
               let chatroom = self.getChatRoomModel(document: doc) {
                print("4")
                chatrooms.append(chatroom)
                print(chatrooms.count)
            } else if let error = error {
                print(error)
            }
        }
        print("5")
        group.leave()
    }
    group.notify(queue: .main) {
        print("5")
        handler(chatrooms)
    }
}

strong text this is what is printed when the function run: [enter image description here][1] i used dispatch group but it doesn't seem to work [1]: https://i.stack.imgur.com/7OE62.png

CodePudding user response:

You have to put the leave statement into the closure to make DispatchGroup work properly

group.enter()
print("enter", id)

db.collection("chatrooms").document(id).getDocument { (document, error) in
    if let doc = document, doc.exists,
       let chatroom = self.getChatRoomModel(document: doc) {
        print("4")
        chatrooms.append(chatroom)
        print(chatrooms.count)
    } else if let error = error {
        print(error)
    }
    print("leave", id)
    group.leave()
}
  • Related