Skip to content

Instantly share code, notes, and snippets.

@jhurliman
Created July 24, 2015 08:00
Show Gist options
  • Save jhurliman/63ee2112e6c5fc036500 to your computer and use it in GitHub Desktop.
Save jhurliman/63ee2112e6c5fc036500 to your computer and use it in GitHub Desktop.
Async.swift
import Foundation
typealias Callback = () -> ()
typealias DoneCallback = (error: NSError?) -> ()
typealias ItemCallback = (i: Int, done: DoneCallback) -> ()
func each(range: Range<Int>, exec: ItemCallback, done: DoneCallback) {
var pending = 0
for i in range {
pending++
runAsync {
exec(i: i) { (error) in
if pending <= 0 { return }
if error != nil {
pending = 0
done(error: error)
return
}
if (--pending <= 0) {
done(error: nil)
}
}
}
}
}
func eachSeries(range: Range<Int>, exec: ItemCallback, done: DoneCallback) {
eachSeriesStep(range.generate(), exec, done)
}
func eachSeriesStep(var generator: RangeGenerator<Int>, exec: ItemCallback, done: DoneCallback) {
if let i = generator.next() {
exec(i: i) { error in
if error != nil {
done(error: error)
return
}
eachSeriesStep(generator, exec, done)
}
} else {
done(error: nil)
}
}
func runAsync(block: dispatch_block_t) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment