作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的method1中,我需要异步调用另一个method2,它返回Option(result1)。比,如果 result1 为空,我需要异步调用另一个 method3,但如果 result1 不为空,我只需要返回它。
这是方法:
def signIn(username: String): Future[User] = {
for {
foundUser <- userService.findByUsername(username) // this method returns Future[Option[User]],
// foundUser is Option[User]
user <- if (foundUser.isEmpty) {
val newUser = User(username = "User123")
userService.create(newUser).map(Some(_)) // this method returns Future[Option[User]]
}
else
// Here I want to return just foundUser, of course, it is not possible.
// IS THIS APPROACH CORRECT?? DOES THIS LINE CREATE ASYNCHRONOUS CALL?
Future.successful(foundUser)
} yield user
}
Future.successful(foundUser)
- 这种方法在上面的代码中是否正确?此行是否创建异步调用?如果是,如何避免?我已经取了
找到用户 异步,我不想进行额外的异步调用只是为了返回已经获取的值。
最佳答案
Future.successful
不会在提供的 ExecutionContext
上排队附加功能.它只是使用 Promise[T]
创建一个完整的Future[T]
:
/** Creates an already completed Future with the specified result.
*
* @tparam T the type of the value in the future
* @param result the given successful value
* @return the newly created `Future` instance
*/
def successful[T](result: T): Future[T] = Promise.successful(result).future
Option.fold
减少样板的数量。 :
def signIn(username: String): Future[User] =
userService
.findByUsername(username)
.flatMap(_.fold(userService.create(User(username = "User123")))(Future.successful(_))
关于Scala Future - 用于理解、混契约(Contract)步和异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39087910/
我是一名优秀的程序员,十分优秀!