数据库获取仅存在于其自身的功能中 [英] Database fetch exists only in its own function

查看:43
本文介绍了数据库获取仅存在于其自身的功能中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取数据库中的所有用户名,但是nameArray仅在函数内部包含值,我该如何解决呢?

I am trying to fetch all the user names in my database but the nameArray only contains values while its inside that function, how can I fix this?

DataService.instance.getAllUserNamesPlease { (returnedNamesArray) in
            self.nameArray = returnedNamesArray
}

for userName in nameArray {
            if(userName.lowercased() == name!.lowercased()){

                self.userNameTaken = true
                self.progressView.progress = Float(progress / self.nameArray.count)
                progress += 1/self.nameArray.count
                break
                }
            }

nameArray在此循环中为空

nameArray is empty in this loop

func getAllUserNamesPlease(handler: @escaping (_ userNames: [String]) -> ()){

        REF_USERS.observeSingleEvent(of: .value) { (userNameSnapshot) in
            guard let userNameSnapshot = userNameSnapshot.children.allObjects as? [DataSnapshot] else {return}
            var namesArray = [String]()
            for names in userNameSnapshot {
                let name = names.childSnapshot(forPath: "userName").value as? String ?? "No Name"
                namesArray.append(name)
            }
            handler(namesArray)
        }
    }

推荐答案

任何需要访问异步调用结果的代码都应位于回调/完成处理程序的内部中.因此,您遍历 nameArray 的循环需要放在 {} 大括号内:

Any code that needs access to the results of an asynchronous call, should be inside that callback/completion handler. So your loop over nameArray, needs to be inside the {} braces:

DataService.instance.getAllUserNamesPlease { (returnedNamesArray) in
    self.nameArray = returnedNamesArray

    for userName in nameArray {
        if(userName.lowercased() == name!.lowercased()){

            self.userNameTaken = true
            self.progressView.progress = Float(progress / self.nameArray.count)
            progress += 1/self.nameArray.count
            break
            }
        }
    }
}

这篇关于数据库获取仅存在于其自身的功能中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆