3

Just reading this article on promises, and the author uses the following example:

def redeemCampaignPledge(): Future[TaxCut] = {
    val p = Promise[TaxCut]()
    Future {
      println("Starting the new legislative period.")
      Thread.sleep(2000)
      //p.success(TaxCut(20))
      //println("We reduced the taxes! You must reelect us 2018!")
      p.failure(LameExcuse("global economy crisis"))
      println("We didn't fullfil our promises, so what?")
    }
    p.future
}

val taxCutF: Future[TaxCut] = redeemCampaignPledge()
  println("Now they're elected, let's see if they remember their promise.")
  taxCutF.onComplete {
    case Success(TaxCut(reduction)) =>
      println(s"Miracle! Taxes cut by $reduction percent.")
    case Failure(ex) =>
    println(s"They broke the promise again. Because of a ${ex.getMessage}")
  }

My question is, can't I just get rid of Promises and rewrite it as:

def redeem(): Future[TaxCut] = Future {
    println("Starting legislative period...!!!!")
    Thread.sleep(2000)

    println("We were successful")
    TaxCut(25)
}

What is this second version lacking? I am not fully grasping the value that promises bring.

Andriy Drozdyuk
  • 58,435
  • 50
  • 171
  • 272

1 Answers1

2

Yes, you are absolutely correct. this is a very common anti pattern with JavaScript Promises (where, Futures are called Promises and Promises are called deferred).

Basically, instead of using the continuations that futures provide, it is building a new continuation around them in a callback like fashion.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Interesting! One case I can think of is "do some work. return result. keep doing work", as in this scala doc (see first example): http://docs.scala-lang.org/overviews/core/futures.html#promises But I can't imagine this is very common? Or can this be implemented with pure futures as well? (I'm thinking you would need two future computations there instead of one) – Andriy Drozdyuk Apr 03 '14 at 19:12
  • 1
    This can be implemented with pure futures as well - make two continuations for the first future. Promises in scala are useful when converting a non future API to futures - for example a callback API or a Java threaded API. – Benjamin Gruenbaum Apr 03 '14 at 19:14