gpt4 book ai didi

Scala Future - 用于理解、混契约(Contract)步和异步

转载 作者:行者123 更新时间:2023-12-05 00:55:02 24 4
gpt4 key购买 nike

在我的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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com