3
votes

I'm trying to get my head around this concept. I clearly understand what Futures are. I'm little bit bemused with Promises. The code snippet below:

val p = Promise[Int]() // gives me a DefaultPromise
val f = p.future // gives me the future computation for the Promise p

Now what is the difference between the following two code snippets?

p success { 10 }

and

val x = Future {
  p success { 10 }
}

My understanding of the first one is that the p success will complete the future computation associated with that p. Is that computation asynchronous? How is that different to the second code snippet that uses a Future block to complete the Future f associated with Promise p?

1
In your example, p success{10} and Future(10) would be equivalent. So Future{ p success { 10 }.future } would be like Future(Future(10)). In few words, you are composing a Promise into a Future. There is a good description here. You can think about Promises like a Future you can write in. When you define p success {x} you are saying that you are going to build a Future that is going to be successful and will return the value x.Carlos Vilchez
A promise is the source of a future. The future is what you can subscribe to. A promise specifies how you create the future.Benjamin Gruenbaum
@Carlos: Thanks for the description. The p success {x} could also result in a failure and is that why we wrap that p success {x} in a Future block?joesan
I recommend you this tutorial: [Promises and futures in practice][1] There for the code that you are asking for, you cand find the explanation for your code: A Promise instance is always linked to exactly one instance of Future. If you call the apply method of Future again in the REPL, you will indeed notice that the Future returned is a Promise, too [1]: danielwestheide.com/blog/2013/01/16/…anquegi
@user3102968, If you think that there is a computation that can fail, you can just wrap it in a in a Future in case the promise is not needed. In other case, If you have a failure you can use p failure trowable.Carlos Vilchez

1 Answers

3
votes

In your example you can consider equivalent p success { 10 } and Future(10). You will only need to extract the future from p to get the same result.

You may consider Promises as a writeable Future where you will define the success or failure of the computation. As it looks a bit imperative programming, you will probably use them in very particular cases. You can see some of those cases in this link.