未来在 Slick 3 中不起作用。1.x

Future not working in Slick 3.1.x

Slick中的这个函数只打印"before future",它不打印future.map内的任何东西;似乎未来永远不会被执行,任何想法可能是什么问题?

注意:我是 运行 Slick standalone,不在 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("???")
      }
   }

您上面的代码不处理未来的失败,future.map 只允许处理成功的结果。

如果在运行db.run(action.asTry)的时候出现crash,未来会失败

处理失败的future,可以使用多种方法,例如:

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

首先 case _ => println("???") 是多余的,我猜你是作为调试语句添加的。此外,您的 SomeRow 永远不会返回,您的 readManyFuture[Unit].

类型

回到你的问题,如果你是 运行 作为一个小代码片段,你可能想要等待你的 Future 完成(记住阻塞在 "real-world" 强烈建议不要申请):

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.