Nesting DispatchSemaphore

202 Views Asked by At

I'm having trouble with the below pattern. I need to synchronously wait for an initial async request, where the completion block in turn calls a list of async calls where each of the async calls need to wait for the previous one to end before it can start.

The below code would call all of the nested requests at once, which is not what I want.

let semaphore = DispatchSemaphore.init(value: 0)
self.getThings { (things) -> (Void) in
    for thing in things {
        self.getSomething { (somevalue) -> (Void) in
        }
    }
    semaphore.signal()
}
semaphore.wait()

So, what I've tried, is to add another semaphore inside the for loop but this has the effect that the nested request are never carried out - it waits indefinitely for semaphore2 signal which never happens. How do I fix this?

let semaphore = DispatchSemaphore.init(value: 0)
self.getThings { (things) -> (Void) in
    for thing in things {
        let semaphore2 = DispatchSemaphore.init(value: 0)
        self.getSomething { (somevalue) -> (Void) in
            semaphore2.signal()
        }
        semaphore2.wait()
    }
    semaphore.signal()
}
semaphore.wait()
0

There are 0 best solutions below