在promises上阅读此article,作者使用以下示例:
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}")
}
我的问题是,我不能摆脱Promise并将其重写为:
def redeem(): Future[TaxCut] = Future {
println("Starting legislative period...!!!!")
Thread.sleep(2000)
println("We were successful")
TaxCut(25)
}
第二个版本缺少什么?我并没有完全理解承诺带来的价值。
答案 0 :(得分:2)
是的,你是绝对正确的。这是一个非常common anti pattern的JavaScript Promises(其中,Futures被称为Promises,Promises被称为延迟)。
基本上,它不是使用期货提供的延续,而是在像时尚这样的回调中围绕它们建立新的延续。