Skip to content

Instantly share code, notes, and snippets.

@petrpavlik
Created November 18, 2016 09:03
Show Gist options
  • Save petrpavlik/6b8d1dafbfd9c452e26abfd2a3100d89 to your computer and use it in GitHub Desktop.
Save petrpavlik/6b8d1dafbfd9c452e26abfd2a3100d89 to your computer and use it in GitHub Desktop.
import Foundation
import HTTP
import Dispatch
public class AsyncRequestGroup {
private enum DummyError: Error {
case dummy
}
public typealias RequestTask = () throws -> Response
public static func execute(tasks: [RequestTask]) -> [Result<Response>] {
let lock = Lock()
let group = DispatchGroup()
var results = [Result<Response>]()
for _ in tasks {
results.append(Result.failure(DummyError.dummy))
}
for i in 0..<tasks.count {
group.enter()
let task = tasks[i]
DispatchQueue.global().async {
do {
let response = try task()
lock.locked(closure: {
results[i] = Result.success(response)
})
} catch {
lock.locked(closure: {
results[i] = Result.failure(error)
})
}
group.leave()
}
}
group.wait()
return results
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment