-
Notifications
You must be signed in to change notification settings - Fork 47
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Refresh view after async response #35
Comments
Hi @newPrimitives, thanks for your question. Swift Express has a Future based asynchronous APIs. You can return Future from your route callback, and then complete it at any time. Something like this import BrightFutures
app.get("/home") { (request:Request<AnyContent>) -> Future<Action<AnyContent>, AnyError> in
// Creating promise
let p = Promise<Action<AnyContent>, AnyError>()
HomeController().fetchData { posts in
//Completing promise with some result
p.success(Action<AnyContent>.render("home", context: ["posts": posts])
}
//Returning future
return p.future
} |
I can suggest a simpler and a more generic way of converting your callbacks based API to Futures. Assuming you have something like this (correct me if I'm wrong): class HomeController {
static func fetchData(callback:(posts: [String])->Void) {
callback(posts: ["post1", "post2"])
}
} add somewhere in your code following function that will convert it to a Future: func futurify<Payload>(fun:((Payload)->Void)->Void) -> Future<Payload, AnyError> {
let p = Promise<Payload, AnyError>()
fun { payload in
p.success(payload)
}
return p.future
} With all above you can handle it as easy as: app.get("/home") { (request:Request<AnyContent>) -> Future<Action<AnyContent>, AnyError> in
return futurify(HomeController.fetchData).map { posts in
Action.render("home", context: ["posts": posts])
}
} Let me know if this worked for you, please. |
@dileping @ypopovych it works. I've implemented this in one of my tutorials which you can check here: http://nermin.tech/swift-on-servers-101-swift-express/ |
@newPrimitives Hey, great article! Thanks ;) There are a couple of things that actually usually work:
Which Xcode have you used and how were you making it work? It works for me...
Usually it works just by quitting Also I'm going to make a PR to your article's code. Just to make it better using async capabilities along with Futures. Best, |
When I render a view and call some async API how do I update that view? I could not find any reload/refresh methods in the docs. For example:
The text was updated successfully, but these errors were encountered: