ps0604
ps0604

Reputation: 1081

Future not working in Slick 3.1.x

This function in Slick only prints "before future", it doesn't print anything within future.map; it seems that the future is never executed, any ideas what could be the problem?

Note: I'm running Slick standalone, not within Play

   def readMany = {
      val db = Database.forURL("jdbc:mysql://localhost:3306/dddd", 
          driver="com.mysql.jdbc.Driver", user="root", password="xxx")
      val query = TableQuery[TableDB]
      val action = query.sortBy(_.name).result
      val future = db.run(action.asTry)
      println("before future")
      future.map{ 
        case Success(s) => {
          s.map {
            row => SomeRow ( row.col1, row.col2 )
          }
          println("s:" + s)
        }
        case Failure(e) => throw new Exception ("Failure in readMany: " + e.getMessage)
        case _ => println("???")
      }
   }

Upvotes: 1

Views: 945

Answers (2)

Federico Pellegatta
Federico Pellegatta

Reputation: 4017

First of all case _ => println("???") is redundant, i guess you added as debug statement. Also your SomeRow is never returned, your readMany is of type Future[Unit].

Going back to your issue, if you are running that as a small code snippet, you may want to wait for your Future to complete (remember that blocking on a future in a "real-world" application is strongly discouraged):

import scala.concurrent.duration._
import scala.concurrent.Await

object Foo extends App {
  def readMany: Future[Unit] = ???
  Await.ready(readMany, 10 seconds)
}

Calling Await.ready waits until the future becomes completed, but does not retrieve its result. In the same way, calling that method will not throw an exception if the future is failed.

Upvotes: 3

Frederic A.
Frederic A.

Reputation: 3514

Your code above doesn't handle failures of the future, future.map only allows to handle successful results.

If there is a crash when running db.run(action.asTry), the future will be failed.

To handle the failed future, you can use various methods, for example:

  • future.recover
  • future.onFailure
  • future.onComplete
  • ...

Upvotes: 1

Related Questions