如何解决我的追加函数的异步性质?
问题描述:
我有一个查询设置为从数据库中提取数据(由heroku托管的Parse-server)并将其附加到数组;在这个查询中是另一个用于从不同类中提取信息的查询,但也用于追加另一个数组。我想因为我使用.findObjectsinBackground
它异步发生,这导致一个问题。下面是代码(广义):如何解决我的追加函数的异步性质?
func getQueries(completion: (() -> Void)?){
let searchQuery = PFQuery(className: "Etc")
searchQuery.findObjectsInBackground(block: { (objects, error) in
if let objectss = objects{
for object in objectss {
//append some arrays
let otherQuery = PFQuery(className: "OtherClass")
otherQuery.whereKey("user", equalTo: object["User"] as String)
otherQuery.findObjectsInBackground(block: {(objects, error) in
if let objectss = objects{
for object in objectss{
array.append(object["ProfPic"] as PFFile)
print("\(array) and its count is \(array.count)") //this returns a non 0 value
}
}
completion!()
})
print("\(array) and its count is \(array.count)") //this returns 0
}
}
})
}
array
的计数返回非0一旦在自己的封闭被追加,但返回0以外的封闭。这是一个问题,因为数组用于迭代显示信息。无论如何要确保在完成searchQuery
的整体关闭之前,otherQuery
的追加程序已经完成? (另外,它发生异步导致问题的事实是猜测......我可能是错的)
答
在后面的例子中,您正在打印计数bofore数据被提取,例如,在findObjectsInBackground
的完成块之外。
你可以用整个事情在自己的方法以完成块:
func fetchData(_ completion:() -> Void) {
searchQuery.findObjectsInBackground(block: { (objects, error) in
guard let objectss = objects else {
completion()
}
for object in objectss {
let otherQuery = PFQuery(className: "OtherClass")
otherQuery.whereKey("user", equalTo: object["User"] as String)
otherQuery.findObjectsInBackground(block: {(objects, error) in
guard let objectss = objects else {
completion()
}
for object in objectss{
array.append(object["ProfPic"] as PFFile)
}
print("In loop: \(array) and its count is \(array.count)")
completion()
})
}
})
}
而且比所有像这样:
fetchData() {
print("After completing: \(array) and its count is \(array.count)")
// do stuff with your fetched data and display it
// "use in iterating through to display information" here
}
更新:
在你更新的问题,你只是在成功的情况下呼叫completion!()
。你必须调用它在任何情况下:
...
if let objectss = objects
...
completion!()
} else {
completion!()
}
...
shallowThought,我试图做你的建议(看看编辑的问题代码块......我把'完成()'在那里...它总是被封装在一个函数中,我只是没有显示那一点)。但是,第二个打印语句仍然返回0.任何想法? –
按照书面说明,您正在打印数据之前的计数。把你的'print()'语句放到你的完成块中(或者在完成!()'调用之前)。正如我编辑的答案。 – shallowThought