gpt4 book ai didi

ios - 如何仅在设置数据后调用完成处理程序?

转载 作者:行者123 更新时间:2023-11-28 13:45:55 24 4
gpt4 key购买 nike

下面看到的函数似乎在 firebase 中设置数据之前通过完成处理程序传递 orderId,这导致使用 orderId 从 Firestore 检索关联数据的后端函数失败。有可能后端函数由于其他原因失败,但可能是因为该函数在传递 orderId 时尚未完成将数据设置为 firestore。如何才能使我的函数仅在设置数据后才提供 orderId?

public func uploadTransactionData(_ menuItems: [MenuItem], tip: Int, tax: Int, rewardAmountApplied: Int, totalPaidFromCredit: Int, discountAmount: Int, subTotal: Int, balanceId: String, locationId: String, completion: @escaping ((String?) -> ())) {
guard let userId = Auth.auth().currentUser?.uid else { completion(nil); return }
let utilitiesManager = UtilitiesManager()
let timestamp = utilitiesManager.timestamp()
var listOfItems = [Any]()
for item in menuItems {
do {
let jsonData = try JSONEncoder().encode(item)
let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: [])
listOfItems.append(jsonObject)
}
catch let err {
print("$-- error uploading transaction data \(err)")
completion(nil)
return
}
}
let orderRef = Firestore.firestore().collection("order").document()
let orderId = orderRef.documentID
let totalPrice = subTotal + tax + tip + discountAmount
let params: [String: Any] = ["date": timestamp,
"total_amount": totalPrice,
"tip_amount": tip,
"tax_amount":tax,
"discount_amount": discountAmount,
"reward_amount": rewardAmountApplied,
"balance_amount": totalPaidFromCredit,
"balance_id": balanceId,
"subtotal": subTotal,
"account_id": userId,
"location_id": locationId,
"status": "PENDING",
"notes": "",
"line_items": listOfItems
]
orderRef.setData(params)
{ err in
if let e = err {
print("$-- error uploading transaction data \(e)")
completion(nil)
} else {
completion(nil)
}
}
completion(orderId)
}

最佳答案

setData 是异步的,在数据​​库生成任何结果之前立即返回。在结果完成之前,您无条件地在函数末尾调用 completion() 。也许你想说这样的话:

orderRef.setData(params)
{ err in
if let e = err {
print("$-- error uploading transaction data \(e)")
completion(nil)
} else {
// Change this line to yield the order id to the callback on success
completion(orderId)
}
}
// Remove this line that always calls the completion before the result
// completion(orderId)

关于ios - 如何仅在设置数据后调用完成处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55381926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com