(Swift)如何同步地制作异步代码



我正在使用Swift制作一个应用程序
我想从FireStore获取数据,但问题是应用程序在完成检索数据之前会继续下一个作业
所以我试着用这个"DispatchSemaphore";代码,但这会阻止应用程序工作
我想知道如何等待getDocument关闭以完成其任务,然后转到下一个。

func changeTerms(uniqueName: String) {
print("colRef: (colRef.document(uniqueName).path)")
let semaphore = DispatchSemaphore(value: 0)
colRef.document(uniqueName).getDocument { snapShot, err in
if let err = err {
self.makeAlerts(title: "Error", message: err.localizedDescription, buttonName: "OK")
} else {
if let doc = snapShot, doc.exists {
if let data = doc.data() {
if let terms = data[K.Fstore.data.attributes] as? [String] {
var temp: [String] = []
for attIdx in self.rankedAttributes {
temp.append(terms[attIdx])
}
self.attributeTerms = temp
print("attributeTerms: (self.attributeTerms)")
self.showTitle()
self.showTerm()
}
}
}
}
semaphore.signal()
}
semaphore.wait()
}

我在Firebase中遇到了同样的问题,我使用withCheckedContinuation()找到了解决方案。你可以在这里了解更多。

您的代码可能是:

let temp: [String] = await withCheckedContinuation { continuation in
colRef.document(uniqueName).getDocument { snapShot, err in
if let err = err {
self.makeAlerts(title: "Error", message: err.localizedDescription, buttonName: "OK")
} else {
if let doc = snapShot, doc.exists {
if let data = doc.data() {
if let terms = data[K.Fstore.data.attributes] as? [String] {
var temp: [String] = []
for attIdx in self.rankedAttributes {
temp.append(terms[attIdx])
}
self.attributeTerms = temp
print("attributeTerms: (self.attributeTerms)")
self.showTitle()
self.showTerm()
}
}
}
}
continuation.resume(returning: temp)
}
}

执行将等待变量temp获得一个值,然后再继续

这仍然是一个异步代码,在后台运行,但它将按顺序运行。

最新更新