问题描述
我是 Vapor 的新手,
我尝试将数据从 postgres 传递到 leaf。
func routes(_ app: Application) throws {
app.get("all") { req -> EventloopFuture<View> in
let todos = Todo.query(on: req.db).all()
let context = TodoContext(todos: todos)
return req.view.render("index",context)
}
}
但是我从上下文行收到一个错误,它说无法将类型“EventLoopFuture”的值转换为预期的参数类型“[Todo]”。
如何将 EventLoopFuture 转换为 '[Todo]' 以便我可以在上下文中使用它? 我在查询 .all() 之后尝试 map 函数,但在此之后它仍然是 EventLoopFuture。
TodoContext:
struct TodoContext: Content {
let todos: [Todos]
}
Todo 模型:
final class Todo: Model,Content {
static let schema = "todo"
@ID(key: .id)
var id: UUID?
@Field(key: "todo")
var todo: String
@Field(key: "complete")
var complete: Bool
init() { }
init(id: UUID? = nil,todo: string,complete: Bool) {
self.id = id
self.todo = todo
self.complete = complete
}
}
解决方法
您是正确的,因为您需要处理未来,但您应该使用 flatMap
,因为渲染调用返回未来。所以你的代码应该是这样的:
func routes(_ app: Application) throws {
app.get("all") { req -> EventloopFuture<View> in
return Todo.query(on: req.db).all().flatMap { todos in
let context = TodoContext(todos: todos)
return req.view.render("index",context)
}
}
}