问题描述
我需要在闭包内调用闭包,并避免出现竞争状况。
当前,我有一个名为 FirebaseUtilities 的类,其中包括与调用Firebase和检索数据有关的所有代码。
应用逻辑
文章包含大量数据,例如标题,摘要,正文,主题等。主题使用以下约定链接到文章:
在此类中,我有一个获取文章的函数:
获取文章的时间段
func fetchArticles(completion: @escaping ([Article]?,Error?) -> Void) {
var subjects = [Subject]()
Database.database().reference().child("articles").observe(.value) { (snapshot) in
// in here i get the value of the snapshot and from there i extract the key of each subject and i store it in an array of String (ex. ["-MD4tN_AjPuCvTUEyZyL"])
// then I call another closure that is responsible for fetching the subjects based on the UID of each subject (see below)
}
})
关闭主题
func fetchSubjects(subjectsUids: [String],completion: @escaping ([Subject]?,Error?) -> Void) {
var subjects = [Subject]()
subjectsUids.forEach { (subjectUid) in
self.dbSubjectsRef.child(subjectUid).observe(.value) { (snapshot) in
guard let subjectDictionary = snapshot.value as? [String: Any] else { return }
let subject = Subject(dictionary: subjectDictionary)
subjects.append(subject)
completion(subjects,nil)
}
}
}
问题
主题数组将始终为空数组,因为它始终比从Firebase提取数据快:
func fetchArticles(completion: @escaping ([Article]?,Error?) -> Void) {
var subjects = [Subject]()
Database.database().reference().child("articles").observe(.value) { (snapshot) in
// in here i get the value of the snapshot and from there i extract the key of each subject and i store it in an array of String (ex. ["-MD4tN_AjPuCvTUEyZyL"])
// then I call another closure that is responsible for fetching the subjects based on the UID of each subject
self.fetchSubjects(subjectsUids: subjectsUids) { (subjectsResults,error) in
guard let sub = subjectsResults else { return }
subjects = sub
// (A) printing here **shows desired results**
print(subjects)
}
// (B) printing here **does not show the results**
// it returns an empty array []
print(subjects)
}
})
我想要什么:
我需要在第二个闭包(self.fetchSubjects(....))之外获取主题数组。
关于如何解决这种比赛条件的任何想法?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)