带期货的findAndModify的返回类型

时间:2014-06-25 19:39:26

标签: scala future reactive-programming

说我正在使用异步库来读写数据。如果失败,我得到一个错误消息作为字符串,否则数据。是否有更好的方式来表示返回类型而不是Future[Either[String, Future[Data]]]

可能的实施:

  def createData(name: String): Future[Either[String, Future[Data]]] = {
    dataDAO.findOneByName(name).flatMap {
      case Some(data) =>
        Future.successful(Left(s"Data with name already exists. $name"))
      case None =>
        val data = Data.createFromName(name)
        dataDAO.save(data).map {
          lastError =>
            data
        }.right.futureSuccessful
      }
    }

1 个答案:

答案 0 :(得分:2)

您的返回类型应为Future[Either[String, Data]]

要归档此内容,您需要将第二种情况更改为:

case None =>
    val data = Data.createFromName(name)
    dataDAO.save(data).map {
      _ => Right(data)
    }

我甚至会将您的错误类型从String改进为CreateDataError,因此您的返回类型为Future[Either[CreateDataError, Data]],您的第一个案例将是

// Having somewhere decalred
trait CreateDataError
object DataAlreadyExistsError

//...
//...

case Some(data) =>
    Future.successful(Left(DataAlreadyExistsError))