作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
下面看到的函数似乎在 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/
我是一名优秀的程序员,十分优秀!