From 4efb5c7aeb3a33fa0bbcdf2766aa8bf9ed8c91ae Mon Sep 17 00:00:00 2001 From: Yuta Koshizawa Date: Sat, 14 Jan 2017 04:38:09 +0900 Subject: [PATCH] Add temporary `_sync` --- Sources/Async.swift | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Sources/Async.swift b/Sources/Async.swift index 27f0540..d504639 100644 --- a/Sources/Async.swift +++ b/Sources/Async.swift @@ -27,6 +27,32 @@ public func sync(operation: (@escaping (T, @escaping (() throws -> R) -> ( } } +public func _sync(operation: (@escaping (T, @escaping (() throws -> R) -> ()) -> ())) -> (T) throws -> R { + return { value in + var resultValue: R! + var resultError: Error? + + let semaphore = DispatchSemaphore(value: 0) + operation(value) { getValue in + defer { + semaphore.signal() + } + do { + resultValue = try getValue() + } catch let error { + resultError = error + } + } + semaphore.wait() + + if let error = resultError { + throw error + } + + return resultValue + } +} + internal func repeated(operation: (@escaping (T, @escaping (() throws -> R) -> ()) -> ()), interval: TimeInterval? = nil) -> ([T], @escaping (() throws -> [R]) -> ()) -> () { return { values, callback in _repeat(operation: operation, for: values[0..