通过循环将数据延迟删除到 Firestore 数组字段值 SWIFT

Delay of delete data into Firestore array field values through loop SWIFT

我正在尝试通过这样的 for 循环删除所有购物车商品:

func removeRelatedProductFromUserCart(selectArrayNodeIds: [String], completion: @escaping(Error?)->()) {
        let semaphore = DispatchSemaphore(value: 0)
        let serialQueue = DispatchQueue(label: "com.queue.Serial")

        serialQueue.async {
            for nodeId in selectArrayNodeIds {
                FirebaseManager.shared.removeProductFromUsersWishOrCartList(isForWishList: false, item: nodeId) { (error) in
                    completion(error)
                    semaphore.signal()
                }
                semaphore.wait()
            }
        }
    }

和 Firebasemanager:

func removeProductFromUsersWishOrCartList(isForWishList: Bool, item: String?, completion: @escaping (Error?) -> ()) {
        let uid = UserDefaults.standard.string(forKey: "uid")!
        if isForWishList == true {
            Firestore.firestore().collection("user").document(uid).updateData([
                "wishList": FieldValue.arrayRemove([item!])
            ]) { (error) in
                completion(error)
            }
        } else {
            Firestore.firestore().collection("user").document(uid).updateData([
                "cart": FieldValue.arrayRemove([item!])
            ]) { (error) in
                completion(error)
            }
        }
    }

然后,当我尝试从同一字段中获取购物车商品时,我在延迟后获得了更新的购物车商品列表。我观察到打开 firebase 控制台的删除过程,我发现删除在控制台中发生延迟。但是错误响应 (error == nill) 并没有等到 removeRelatedProductFromUserCart。那么我如何才能等到删除 Firestore 上的所有购物车项目然后加载它们呢?提前致谢。

1- Firebase 在后台线程中运行,因此不需要

let serialQueue = DispatchQueue(label: "com.queue.Serial")

2- 你需要 DispatchGroup

func removeRelatedProductFromUserCart(selectArrayNodeIds: [String], completion: @escaping(Bool)->()) {

           let g = DispatchGroup() 
            for nodeId in selectArrayNodeIds {
                 g.enter()
                 FirebaseManager.shared.removeProductFromUsersWishOrCartList(isForWishList: false, item: nodeId) { (error) in  
                   q.leave()
                } 
            } 
         g.notify(queue:.main) {
            completion(true)
         }
}