斯卡拉承诺澄清

时间:2014-12-02 19:00:32

标签: scala

如果在Scala中你是否能够成功实现这样的承诺,那就快速提出问题;

 val successful = Promise[List[T]]()     //Create a promise which will be returning the results
 successful.success(Nil)   

这不会完成承诺,因此不会允许你进一步写下承诺吗?哪个也会触发完成回调的承诺?

我问的原因是我正在尝试理解下面这段代码,并且我试图理解为什么在计算未来甚至开始之前,承诺是用Nil初始化的。

def all[T](fs: List[Future[T]]): Future[List[T]] = {
  val successful = Promise[List[T]]()     //Create a promise which will be returning the results
  successful.success(Nil)                 //Initialize the profile
  fs.foldRight(successful.future) {       //Create the Aggregate for the fold right which will be an empty future
    //for each element extract the element from the future and append to our aggregate
    //f -> Future[T] acc -> Future[List[T]]
    (f, acc) => for { x <- f; xs <- acc } yield x :: xs
  }
}

大声思考我会说完成承诺的原因是没有附加callbacsk,因此我们不关心它什么时候成功。如果是这样,使用承诺的唯一原因就是利用它的未来。那么,如果不使用我们实际上不需要的承诺来定义未来,他们是不是更简单/更清洁的方式?

1 个答案:

答案 0 :(得分:1)

是的,承诺只完成一次(我不确定你的意思&#34; onComplete回调&#34;我在标准库{{1}中看不到这样的事情} docs)。但是,即使承诺已经完成,承诺的Promise当然可以使用并按预期工作。这似乎是使用future作为Future.successful(Nil)的初始元素的过于复杂的方式。