Reputation: 5411
I have some code that i want to run asynchronously in a request. That code has no effect on the response so i run it like this
import scala.concurrent.Future
Database.forURL(url, driver = driver) withSession {
implicit session =>
// some db changes
//some code that has effect on response like getting userId
//so run synchronously
// now asynchronous code
import play.api.libs.concurrent.Execution.Implicits.defaultContext
Future {
println("inside Futute, starting")
val userAuthTable = TableQuery[Tables.UserAuth]
println("inside Futute, running")
// some db operations
println("inside Futute, done")
} // Future block ends
userId
} // session ends
Here i can see the 2 lines print on the console
inside Futute, starting
and
inside Futute, running
but i dont see
inside Futute, done
Neither the db operations
are done. I am able to get userId
which is outside Future
. When i put those db operations outside the Future
, they get executed. But why not inside the Future
? And why the first 2 lines get printed on the console. I am using play 2.3.3
and scala 2.11
.
Update
My code was in a Postgres Session and somehow Future
block gets executed outside of scope of session. So i created 2 sessions, one for executing the db code
synchronously and the other for asynchronous code inside the Future
. This works correctly
import scala.concurrent.Future
val userId = Database.forURL(url, driver = driver) withSession {
implicit session =>
// some db changes
//some code that has effect on response like getting userId
//so run synchronously
} // session ends
// now asynchronous code
import play.api.libs.concurrent.Execution.Implicits.defaultContext
Future {
println("inside Futute, starting")
Database.forURL(url, driver = driver) withSession {
implicit session =>
val userAuthTable = TableQuery[Tables.UserAuth]
println("inside Futute, running")
// some db operations
} // session ends
println("inside Futute, done")
} // Future ends
Thanks to @Ryan and @applicius
Upvotes: 1
Views: 124
Reputation: 7257
Add a .recover
to the end of your future to make sure an exception isn't being thrown and ignored.
Upvotes: 2