使用 GCD 等待异步函数完成

Waiting for async function to finish using GCD

我有一个查询 Parse 的异步函数。在调用我的第二个函数之前,我需要等到 Parse 查询中的所有对象都已返回。问题是,我正在使用:

          var group: dispatch_group_t = dispatch_group_create()

          dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { () -> Void in

                asyncFunctionA() // this includes an async Parse query

            }

          dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { () -> Void in

                asyncFunctionB() // must be called when asyncFunctionA() has finished

            }

...但是,在我将任何对象附加到 asyncFunctionA() 中的数组之前,asyncFunctionB() 就被调用了。使用 GCD 通知不是为了观察先前功能的完成吗?为什么它在这里不起作用?

就像 Parse 使用完成的概念 block/closures,你需要在你的 asyncFunctionA:

中做同样的事情
func asyncFunctionA(completionHandler: () -> ()) {
    // your code to prepare the background request goes here, but the
    // key is that in the background task's closure, you add a call to
    // your `completionHandler` that we defined above, e.g.:

    gameScore.saveInBackgroundWithBlock { success, error in
        if (success) {
            // The object has been saved.
        } else {
            // There was a problem, check error.description
        }

        completionHandler()
    }
}

然后你可以像你的代码片段那样做一些事情:

let group = dispatch_group_create()

dispatch_group_enter(group)
asyncFunctionA() {
    dispatch_group_leave(group)
}

dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
    self.asyncFunctionB()
}

注意,如果函数 A 确实使用了 Parse 的异步方法,那么就没有必要在那里使用 dispatch_async。但是,如果您出于某种原因需要它,请随时将其添加回去,但要确保 之前发生 以分派到某个后台线程。

坦率地说,如果我将一大堆项目添加到这个组,我只会使用组。如果真的只是 B 在等待对 A 的单个调用,我会完全退出这些组,然后执行以下操作:

asyncFunctionA() {
    self.asyncFunctionB()
}