Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jordanebelanger/08e235d8c34df3ef61a53abc07a00e8b to your computer and use it in GitHub Desktop.
Save jordanebelanger/08e235d8c34df3ef61a53abc07a00e8b to your computer and use it in GitHub Desktop.
Sync syntax Vapor route
import class Dispatch.DispatchQueue
import NIO
public extension DispatchQueue {
/// `DispatchQueue.async` but returning a NIO future wrapping the closure return.
func async<Value>(on eventLoop: EventLoop, use closure: @escaping () throws -> Value) -> EventLoopFuture<Value> {
let promise = eventLoop.makePromise(of: Value.self)
async {
do {
promise.succeed(try closure())
} catch {
promise.fail(error)
}
}
return promise.futureResult
}
}
import Vapor
import Fluent
func routes(_ app: Application) throws {
app.get("hello") { req -> EventLoopFuture<Todo> in
return DispatchQueue.global().async(on: req.eventLoop) {
let todo = Todo(title: "Synchronous synthax")
try todo.save(on: req.db).wait()
return todo
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment