考虑以下嵌套的平面图结构:
val isValid: F[Boolean] = userRepository.isValid(username, password)
isValid.flatMap(valid =>
if (valid) {
userRepository.getClaims(username).flatMap(claims => {
val token = JWTRefreshService.createToken(claims)
Created(token)
}
)
} else {
Unauthorized(headers.`WWW-Authenticate`(NonEmptyList.of(Challenge(scheme = "Bearer", realm =
"Access to authorize a request"))))
}
)
Run Code Online (Sandbox Code Playgroud)
哪里F是F[_] : Sync。
我怎样才能把这个结构改写成 for-comprehension。我无法弄清楚如何在不创建嵌套 for-comprehension 的情况下重写 if else 子句。
在我当前的项目中,我使用Either[Result, HandbookModule]( Resultis an HTTP Statuscode) 作为返回类型,以便在出现问题时创建正确的状态。我现在已经将我的数据库访问重构为非阻塞。
此更改要求我的数据库访问函数的返回类型更改为Future[Either[Result, HandbookModule]].
现在我不确定如何将此函数与另一个返回Either[Result, Long].
所以为了更好地说明我的意思:
def moduleDao.getHandbooks(offset, limit): Future[Either[Result, List[Module]] = Future(Right(List(Module(1))))
def nextOffset(offset, limit, results): Either[_, Long] = Right(1)
def getHandbooks(
offset: Long,
limit: Long): Future[Either[Result, (List[HandbookModule], Long)]] = {
for {
results <- moduleDao.getHandbooks(offset, limit)
offset <- nextOffset(offset, limit, results)
} yield (results, offset)
}
Run Code Online (Sandbox Code Playgroud)
在更改之前,这显然没有问题,但我不知道最好的方法是什么。
或者有没有办法将 a 转换Future[Either[A, B]]为 an Either[A, Future[B]]?