簡體   English   中英

僅在設置了數據后如何調用完成處理程序?

[英]How do I call the completion handler only once the data has been set?

在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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM