如何使用 DispatchGroup 在 for 循环中进行异步调用

How to use DispatchGroup to make asynchronous calls within a for loop

在下面的示例代码中,我在失败时调用 complete(false)。但是,由于我使用 DispatchGroup 对象来确保所有异步请求都已完成,所以我不能只在失败时调用 syncGroup.leave(),因为将调用 notify,其中包含 complete(true),使此函数 return true,当它应该 returning false 失败时。

我没有在未能正确完成我的功能时调用 syncGroup.leave() 是否正确?或者我应该调用 syncGroup.leave() 并以某种方式尝试确定结果是什么,以便我可以 return false 失败?

let syncGroup = DispatchGroup()
syncGroup.enter()
for track in unsynced {
    register(time: time, withCompletion: { (success: Bool) -> () in

        if success {
            self.debug.log(tag: "SyncController", content: "Registered")
            syncGroup.leave()
        }
        else {
            complete(false)
        }
    })
}

//all requests complete
syncGroup.notify(queue: .main) {
    self.debug.log(tag: "SyncController", content: "Finished registering")
    complete(true)
}

您必须在 for 循环中输入组。您可能想引入一个额外的错误标志。

示例实现:

    var fail = false
    let syncGroup = DispatchGroup()

    for track in unsynced {
        syncGroup.enter()
        register(time: time, withCompletion: { (success: Bool) -> () in

            if success {
                self.debug.log(tag: "SyncController", content: "Registered")
                syncGroup.leave()
            }
            else {
                fail = true
                syncGroup.leave()
            }
        })
    }

    //all requests complete
    syncGroup.notify(queue: .main) {
        if fail {
            complete(false)

        } else {
            self.debug.log(tag: "SyncController", content: "Finished registering")
            complete(true)
        }
    }