我正在尝试使用相同的请求对象创建一个实体Task和一个孩子
func create(_ req: Request) throws -> Future<Response> {
return try req.content.decode(Task.TaskForm.self).flatMap { taskForm in
let user = try req.requireAuthenticated(User.self)
let task = Task(name: taskForm.name, userId: user.id!)
return task.save(on: req).map { t in
let interval = try Interval(taskId: t.requireID())
let t = interval.save(on: req)
return t.save(on: req).map { _ in
return req.redirect(to: "/dashboard")
}
}
}
}
我得到的错误是这个:
无法将“ EventLoopFuture”类型的返回表达式转换为“ Response”类型。
有什么问题的想法吗?
答案 0 :(得分:1)
此代码应该有效
func create(_ req: Request) throws -> Future<Response> {
return try req.content.decode(Task.TaskForm.self).flatMap { taskForm in
let user = try req.requireAuthenticated(User.self)
let task = Task(name: taskForm.name, userId: user.id!)
return task.create(on: req).flatMap { t in
let interval = try Interval(taskId: t.requireID())
return interval.create(on: req).flatMap { _ in
return t.create(on: req).transform(to: req.redirect(to: "/dashboard"))
// or your previous variant
// return t.create(on: req).map { _ in
// return req.redirect(to: "/dashboard")
// }
}
}
}
}
您可以学到一些东西
map
flatMap
您必须返回Future<>
结果create
代替save