Why doesn't onComplete wait for Promise.success in the code in Scala?
scala
Solution
My guess is that this has to do with the `ExecutionContext` you are using daemon threads and thus terminating when your `main` gets past the `onComplete`. If you add a sleep after the `onComplete`, you should get what you want. A slightly modified version of your code showing this:
import concurrent._
import ExecutionContext.Implicits._
object PromTest {
def printSomething(): Future[String] = {
val p = Promise[String]
val sayHello = future {
Thread.sleep(1000)
p.success("hello")
}
p.future
}
def main(args: Array[String]) {
val something: Future[String] = printSomething()
something onComplete {
case result => println(result)
}
Thread.sleep(2000)
}
}
Problem
I'm reading about Futures and Promises in Scala and wrote the following code: ``` def printSomething(): Future[String] = { val p = Promise[String] val sayHello = future { Thread.sleep(1000) p.success("hello") } p.future } def main(args: Array[String]) { val something: Future[String] = printSomething() something onComplete { case Success(p) => println(p) } } ``` The problem is the `onComplete` callback doesn't `print` anything (unless I debug it). Wouldn't the `onComplete` have to wait for the `p.success("hello")` in the `printSomething` ?