swift - 尝试转换 EventLoopFuture 时出错输入
问题描述
我是一般编码的新手,尤其是期货的概念,所以耐心等待将不胜感激!以下函数的目标是检查 PostgreSQL 数据库中是否存在帐户。如果是,则返回一个空的 UUID;如果不存在帐户,则创建一个新帐户并返回其 UUID。当我尝试运行我的代码时,错误Cannot convert return expression of type 'EventLoopFuture<Account.idOut>' to return type 'Account.idOut'
出现在.map { Account.idOut(id: account.id!) }
. 我已经在这里环顾四周,似乎找不到任何解决此问题的方法。任何帮助将不胜感激,谢谢!!
func newAccount(req: Request) throws -> EventLoopFuture<Account.idOut> {
let input = try req.content.decode(Account.postAccount.self)
//check to see if account already exists
return Account.query(on: req.db)
.filter(\.$email == input.email)
.first().map { checkAccount in
if checkAccount == nil {
let id = UUID()
let account = Account(id: id, fullName: input.fullName, email: input.email, password: input.password, type: input.type)
return account.save(on: req.db)
.map { Account.idOut(id: account.id!) }
} else {
return Account.idOut(id: UUID("00000000-0000-0000-0000-000000000000")!)
}
}
}
解决方案
总之,你需要返回相同的类型来满足编译器。if
这肯定会与/ like yours有点混淆,else
其中一个返回未来而一个不返回。解决它的方法是为两者返回一个未来,如下所示:
func newAccount(req: Request) throws -> EventLoopFuture<Account.idOut> {
let input = try req.content.decode(Account.postAccount.self)
//check to see if account already exists
return Account.query(on: req.db)
.filter(\.$email == input.email)
.first().flatMap { checkAccount in
if checkAccount == nil {
let id = UUID()
let account = Account(id: id, fullName: input.fullName, email: input.email, password: input.password, type: input.type)
return account.create(on: req.db)
.map { Account.idOut(id: account.id!) }
} else {
return req.eventLoop.future(Account.idOut(id: UUID("00000000-0000-0000-0000-000000000000")!))
}
}
}
需要注意的重要事项:
- 我把第一个改成
map
a,flatMap
因为你在里面返回一个未来 - 当您提供 ID时,我使用
create
而不是保存操作,这会强制 Fluent 创建模型。save
(Fluent 通常会为你设置 ID) - 我将帐户包裹在其中
req.eventLoop.future
-返回EventLoopFuture<Account.idOut>
满足编译器的要求
推荐阅读
- java - 在创建通用 CRUD 组件时使用聚合而不是继承会更好吗?
- oracle - Oracle SQL Developer 12505 网络更改后的错误
- python - 词云 MatplotLib
- python - 更高效的脚本
- sql - 跨数据库会话保持多用户状态
- sql - 最多一个查询 SQL
- c# - 成功消息后如何重定向登录页面
- byte-buddy - 有什么办法可以让byte buddy生成的这个类文件包含LocalVariableTable?
- loopbackjs - Loopback 4:如何从 loopback 4 访问名称中带有下划线的表?
- python - 如何使用列表推导将函数列表应用于参数列表