Created
November 18, 2016 09:03
-
-
Save petrpavlik/6b8d1dafbfd9c452e26abfd2a3100d89 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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