如何在返回variables之前等待firebase将数据加载到variables中然后调用函数

这个问题不是重复的。

所以我有一个简单的函数,它将获取tableview单元格被点击的索引的参数,所以函数将进入didSelectRowAt tableView函数,它也将返回一个string。

该函数被称为getOpposingUserName,它连接到firebase以收集数据库内提供的信息。

现在我知道函数的function起作用了,这是一种逻辑错误,我不太明白。 从我所知道的是,无论何时您尝试从Firebase获取数据,它都会运行该代码,并花费一秒时间来实际获取数据。 但是因为它这样做,它会继续运行下面的代码,试图从数据库中获取数据。

这意味着如果我想返回一个string,那么string将永远是零或无论我设置其初始值,因为数据库将花费很长的时间来加载和函数已经跑过代码返回的东西。我对它的理解,我敢肯定有更多的技术方式来解释它)

所以基本上我问的是如何将数据“加载”到variables中,然后检查firebase是否已经将某些东西加载到variables中,然后将该variables返回给函数

这个问题不是重复的我已经阅读了这个问题,试图在我自己的实现中理解它。 当我阅读代码时,我不会返回一个代码让我感到困惑的函数。

这里是我的代码的function

func getOpposingUsername(_ index: Int) -> String { var opposingUser: String = "" //the self.tieBetToUser just gets the randomized id from the bet in firebase don't need to worry about it self.datRef.child("Bets").child(self.tieBetToUser[index]).observe(.childAdded, with: { snapshot in guard let dict = snapshot.value as? [String: AnyHashable] else { return } opposingUser = dict["OpposingUsername"] as! String print(opposingUser) //this code actually never runs I found out }) //sleep(4) this will not work and is actually bad code anyway different phones may be faster or slower return opposingUser // will always return "" at the moment } 

这是互联网提供的解决scheme

 typealias someting = (String?) -> Void func getOpposingUsername(completionHandler: @escaping someting, _ index: Int) { var opposingUser: String = "" self.datRef.child("Bets").child(self.tieBetToUser[index]).observe(.childAdded, with: { snapshot in guard let dict = snapshot.value as? [String: AnyHashable] else { return } opposingUser = dict["OpposingUsername"] as! String if opposingUser.isEmpty { completionHandler(nil) } else { completionHandler(opposingUser) } }) } 

我到底该怎么称呼这个function呢? 像getOpposingUsername(somethingGoesHere,index.path)