firebase函数中的firebase函数

Firebase function in firebase function

下面的函数要return我所有用户的好友列表。但是,它只对其中一个朋友这样做。我知道这是因为 2 个 firebase 函数是 运行 异步的,但是我不确定我必须更改函数以使其按应有的方式运行。即检索所有好友。

///retrieves all of user's friends
    func fetchFriends(completion: @escaping ([FriendModel])->()){
        FRIEND_REQ_REF.child(CURRENT_USER_ID).observe(.childAdded, with: {(snapshot) in
            var friends = [FriendModel]()
            if snapshot.value as? Int == 0 {
                self.USERS_REF.child(snapshot.key).observeSingleEvent(of: .value, with: {(snap) in
                    if let dictionary = snap.value as? [String : AnyObject]{
                        let friend = FriendModel()
                        friend.setValue(dictionary["userName"], forKey: "userName")
                        friend.setValue(dictionary["name"], forKey: "name")
                        friends.append(friend)
                        completion(friends)
                    }
                })
            }
        })
    }

这是我的数据结构:

FRIEND_REQ_REF
              firebaseUserID
                 friendFirebasegivenID : 0
                 anotherFriendFirebasegivenID : 0
USERS_REF
            friendFirebasegivenID
                 userName : String 
                 name : String 
            anotherFriendFirebasegivenID : 0
                 userName : String 
                 name : String 
///retrieves all of user's friends
    func fetchFriends(completion: @escaping ([FriendModel])->()){
        FRIEND_REQ_REF.child(CURRENT_USER_ID).observe(.value, with: {(snapshot) in
            var friends = [FriendModel]()

            if let dict = snapshot.value as? [String : AnyObject] {
                for (_,k) in dict.enumerated() {

                    if k.value == 0 {

                        self.USERS_REF.child(k.key).observeSingleEvent(of: .value, with: {(snap) in
                    if let dictionary = snap.value as? [String : AnyObject]{
                        let friend = FriendModel()
                        friend.setValue(dictionary["userName"], forKey: "userName")
                        friend.setValue(dictionary["name"], forKey: "name")
                        friends.append(friend)
                        completion(friends)
                    }
                })
                    }


                }
            }

        })
    }