我正在尝试编写一个简单的数据库查询来从实时数据库中获取一些数据,我想使用异步/等待,但我不知道是否可以使用
observeSingleEvent
可以做这样的事情吗?
func getPromoCodes() async throws -> [PromoCode] {
promoCodes.observeSingleEvent(of: .value) { snap in
guard let snap = snap.value as? [String: Any] else {
return []
}
do {
let jsonData = try JSONSerialization.data(withJSONObject: snap)
let decoded = try JSONDecoder().decode([PromoCode].self, from: jsonData)
return decoded
} catch {
return []
}
}
}
事实证明它非常简单,每个 DatabaseReference 都有一个异步
getData
函数
func getPromoCodes() async throws -> [PromoCode] {
let data = try await promoCodes.getData()
print("DATA HERE: \(data)")
guard let data = data.value as? [String: Any] else {
return []
}
do {
let jsonData = try JSONSerialization.data(withJSONObject: data)
let decoded = try JSONDecoder().decode([String: PromoCode].self, from: jsonData)
return decoded.map({ $0.value })
} catch {
print("DECODE: \(error)")
return []
}
}
func add(company: Company) async -> Result<Company, Error> {
do {
let company = try await collection_company.addDocument(from: company).getDocument().data(as: Company.self)
return .success(company)
} catch {
return .failure(error)
}
}
func retrieve(id: String) async -> Result<[Company], Error> {
do {
let snapshot = try await collection_company.whereField("owner", isEqualTo: id).getDocuments()
let documents = snapshot.documents
return .success(documents.compactMap({ try? $0.data(as: Company.self) }))
} catch {
return .failure(error)
}
}
func update(company: Company) async {
guard let id = company.id else { return }
do {
try collection_company.document(id).setData(from: company)
} catch {
print(error.localizedDescription)
}
}
func delete(company: Company) async {
do {
guard let id = company.id else { return }
try await collection_company.document(id).delete()
}
catch {
print(error.localizedDescription)
}
}
阅读本文可以更好地理解 async-await 机制的基础 这里