Vistritium Vistritium - 1 month ago 8
Scala Question

How to complete request with Future[StandardRoute]

I have code that simplified looks like this:

path("path") {
post {
val routeFuture: Future[StandardRoute] = Future {
//some app logic
utilFunctionRoute()
}

??? // complete the request
}
}


At one point I have Future[StandardRoute] that contains my result but I don't know how can I complete this request without blocking on Future.

Answer

You can use onComplete to complete the request when dealing with futures without blocking. onComplete takes the future and then we can pattern match on success and failure to prepare the Http Response.

path("path")  {
  post {
    val routeFuture: Future[StandardRoute] = Future {
      utilFunctionRoute()
    }

    onComplete(routeFuture){
      case util.Success(f) =>
        complete(StatusCodes.OK)

      case util.Failure(ex) =>
        complete(StatusCodes.InternalServerError )
  }
}