简体   繁体   English

如何避免Await.result?

[英]How to avoid Await.result?

I have my Play app, and I want to implement kind of uniqueness validation by myself, I use Slick , so it's natural that I do a simple sum(1) where call and if that count is more than zero I set the error to my case class object . 我有我的Play应用,我想自己实现一种唯一性验证,我使用Slick ,所以很自然地我做一个简单的sum(1) where call,如果该count大于零,则将错误设置为case class object So I can't imagine the workaround to avoid Await.result on my DB query, because I need to set the error right in the current time. 因此,我无法想像在我的数据库查询中避免Await.result的解决方法,因为我需要在当前时间正确设置错误。

But I now that Await.result is really bad practice, any suggestions ? 但是我现在认为Await.result确实是不好的做法,有什么建议吗?

You should use map on the future: 您应该在将来使用map:

db.run(query.result) map { response =>
  //do whatever you want with the response
}

In this case you get the response but it is not blocking as Await.result is. 在这种情况下,您会收到响应,但不会像Await.result那样阻塞。

Edit: so for the code you showed in your comment, it would look like: 编辑:因此对于您在注释中显示的代码,它看起来像:

def exists(tableName: String, column: String, value: Any): Future[Boolean] = {
  val query = dbConfig.db.run(sql"SELECT COUNT(1) from #$tableName WHERE #$column = ${value.toString};".as[Int])

  query.map(_.sum > 0)
}

Then where you need to call exists you will do 然后,你需要调用exists ,你会做

exists(...) map  { result => 
if (result == true) 
  //doSomething
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM