Created
August 21, 2020 03:00
-
-
Save jordanebelanger/08e235d8c34df3ef61a53abc07a00e8b to your computer and use it in GitHub Desktop.
Sync syntax Vapor route
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 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 | |
} | |
} |
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 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