如何在 Scala 中使用函数 returning Future(Either[A, B]) 中的 return 值?
How to use return value from function returning Future(Either[A, B]) in scala?
我有以下功能。
def get(id: Int): Future[Either[String, Item]] = {
request(RequestBuilding.Get(s"/log/$id")).flatMap { response =>
response.status match {
case OK => Unmarshal(response.entity).to[Item].map(Right(_))
case BadRequest => Future.successful(Left(s"Bad Request"))
case _ => Unmarshal(response.entity).to[String].flatMap { entity =>
val error = s"Request failed with status code ${response.status} and entity $entity"
Future.failed(new IOException(error))
}
}
}
}
我正在尝试调用此函数,但我不确定如何知道它返回的是字符串还是项目。以下是我失败的尝试。
Client.get(1).onComplete { result =>
result match {
case Left(msg) => println(msg)
case Right(item) => // Do something
}
}
onComplete
采用 Try
类型的函数,因此您必须在 Try
上进行双重匹配,如果在 Either
上成功
Client.get(1).onComplete {
case Success(either) => either match {
case Left(int) => int
case Right(string) => string
}
case Failure(f) => f
}
绘制未来地图会容易得多:
Client.get(1).map {
case Left(msg) => println(msg)
case Right(item) => // Do something
}
如果您想处理 onComplete
的 Failure
部分,请在映射到未来后使用 recover
或 recoverWith
。
我有以下功能。
def get(id: Int): Future[Either[String, Item]] = {
request(RequestBuilding.Get(s"/log/$id")).flatMap { response =>
response.status match {
case OK => Unmarshal(response.entity).to[Item].map(Right(_))
case BadRequest => Future.successful(Left(s"Bad Request"))
case _ => Unmarshal(response.entity).to[String].flatMap { entity =>
val error = s"Request failed with status code ${response.status} and entity $entity"
Future.failed(new IOException(error))
}
}
}
}
我正在尝试调用此函数,但我不确定如何知道它返回的是字符串还是项目。以下是我失败的尝试。
Client.get(1).onComplete { result =>
result match {
case Left(msg) => println(msg)
case Right(item) => // Do something
}
}
onComplete
采用 Try
类型的函数,因此您必须在 Try
上进行双重匹配,如果在 Either
Client.get(1).onComplete {
case Success(either) => either match {
case Left(int) => int
case Right(string) => string
}
case Failure(f) => f
}
绘制未来地图会容易得多:
Client.get(1).map {
case Left(msg) => println(msg)
case Right(item) => // Do something
}
如果您想处理 onComplete
的 Failure
部分,请在映射到未来后使用 recover
或 recoverWith
。